babylon.viewer.max.js 5.2 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943
  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.5";
  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. /**
  17809. * Creates a new bounding sphere
  17810. * @param min defines the minimum vector (in local space)
  17811. * @param max defines the maximum vector (in local space)
  17812. */
  17813. function BoundingSphere(min, max) {
  17814. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17815. this.reConstruct(min, max);
  17816. }
  17817. /**
  17818. * Recreates the entire bounding sphere from scratch
  17819. * @param min defines the new minimum vector (in local space)
  17820. * @param max defines the new maximum vector (in local space)
  17821. */
  17822. BoundingSphere.prototype.reConstruct = function (min, max) {
  17823. this.minimum = min.clone();
  17824. this.maximum = max.clone();
  17825. var distance = BABYLON.Vector3.Distance(min, max);
  17826. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17827. this.radius = distance * 0.5;
  17828. this.centerWorld = BABYLON.Vector3.Zero();
  17829. this._update(BABYLON.Matrix.Identity());
  17830. };
  17831. // Methods
  17832. BoundingSphere.prototype._update = function (world) {
  17833. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17834. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17835. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17836. };
  17837. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17838. for (var i = 0; i < 6; i++) {
  17839. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17840. return false;
  17841. }
  17842. return true;
  17843. };
  17844. BoundingSphere.prototype.intersectsPoint = function (point) {
  17845. var x = this.centerWorld.x - point.x;
  17846. var y = this.centerWorld.y - point.y;
  17847. var z = this.centerWorld.z - point.z;
  17848. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17849. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17850. return false;
  17851. return true;
  17852. };
  17853. // Statics
  17854. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17855. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17856. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17857. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17858. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17859. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17860. return false;
  17861. return true;
  17862. };
  17863. return BoundingSphere;
  17864. }());
  17865. BABYLON.BoundingSphere = BoundingSphere;
  17866. })(BABYLON || (BABYLON = {}));
  17867. //# sourceMappingURL=babylon.boundingSphere.js.map
  17868. var BABYLON;
  17869. (function (BABYLON) {
  17870. var BoundingBox = /** @class */ (function () {
  17871. /**
  17872. * Creates a new bounding box
  17873. * @param min defines the minimum vector (in local space)
  17874. * @param max defines the maximum vector (in local space)
  17875. */
  17876. function BoundingBox(min, max) {
  17877. this.vectorsWorld = new Array();
  17878. this.reConstruct(min, max);
  17879. }
  17880. // Methods
  17881. /**
  17882. * Recreates the entire bounding box from scratch
  17883. * @param min defines the new minimum vector (in local space)
  17884. * @param max defines the new maximum vector (in local space)
  17885. */
  17886. BoundingBox.prototype.reConstruct = function (min, max) {
  17887. this.minimum = min.clone();
  17888. this.maximum = max.clone();
  17889. // Bounding vectors
  17890. this.vectors = new Array();
  17891. this.vectors.push(this.minimum.clone());
  17892. this.vectors.push(this.maximum.clone());
  17893. this.vectors.push(this.minimum.clone());
  17894. this.vectors[2].x = this.maximum.x;
  17895. this.vectors.push(this.minimum.clone());
  17896. this.vectors[3].y = this.maximum.y;
  17897. this.vectors.push(this.minimum.clone());
  17898. this.vectors[4].z = this.maximum.z;
  17899. this.vectors.push(this.maximum.clone());
  17900. this.vectors[5].z = this.minimum.z;
  17901. this.vectors.push(this.maximum.clone());
  17902. this.vectors[6].x = this.minimum.x;
  17903. this.vectors.push(this.maximum.clone());
  17904. this.vectors[7].y = this.minimum.y;
  17905. // OBB
  17906. this.center = this.maximum.add(this.minimum).scale(0.5);
  17907. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17908. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17909. // World
  17910. for (var index = 0; index < this.vectors.length; index++) {
  17911. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17912. }
  17913. this.minimumWorld = BABYLON.Vector3.Zero();
  17914. this.maximumWorld = BABYLON.Vector3.Zero();
  17915. this.centerWorld = BABYLON.Vector3.Zero();
  17916. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17917. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17918. };
  17919. BoundingBox.prototype.getWorldMatrix = function () {
  17920. return this._worldMatrix;
  17921. };
  17922. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17923. this._worldMatrix.copyFrom(matrix);
  17924. return this;
  17925. };
  17926. BoundingBox.prototype._update = function (world) {
  17927. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17928. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17929. for (var index = 0; index < this.vectors.length; index++) {
  17930. var v = this.vectorsWorld[index];
  17931. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17932. if (v.x < this.minimumWorld.x)
  17933. this.minimumWorld.x = v.x;
  17934. if (v.y < this.minimumWorld.y)
  17935. this.minimumWorld.y = v.y;
  17936. if (v.z < this.minimumWorld.z)
  17937. this.minimumWorld.z = v.z;
  17938. if (v.x > this.maximumWorld.x)
  17939. this.maximumWorld.x = v.x;
  17940. if (v.y > this.maximumWorld.y)
  17941. this.maximumWorld.y = v.y;
  17942. if (v.z > this.maximumWorld.z)
  17943. this.maximumWorld.z = v.z;
  17944. }
  17945. // Extend
  17946. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17947. this.extendSizeWorld.scaleInPlace(0.5);
  17948. // OBB
  17949. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17950. this.centerWorld.scaleInPlace(0.5);
  17951. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17952. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17953. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17954. this._worldMatrix = world;
  17955. };
  17956. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17957. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17958. };
  17959. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17960. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17961. };
  17962. BoundingBox.prototype.intersectsPoint = function (point) {
  17963. var delta = -BABYLON.Epsilon;
  17964. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17965. return false;
  17966. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17967. return false;
  17968. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17969. return false;
  17970. return true;
  17971. };
  17972. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17973. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17974. };
  17975. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17976. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17977. return false;
  17978. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17979. return false;
  17980. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17981. return false;
  17982. return true;
  17983. };
  17984. // Statics
  17985. BoundingBox.Intersects = function (box0, box1) {
  17986. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17987. return false;
  17988. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17989. return false;
  17990. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17991. return false;
  17992. return true;
  17993. };
  17994. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17995. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17996. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17997. return (num <= (sphereRadius * sphereRadius));
  17998. };
  17999. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18000. for (var p = 0; p < 6; p++) {
  18001. for (var i = 0; i < 8; i++) {
  18002. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18003. return false;
  18004. }
  18005. }
  18006. }
  18007. return true;
  18008. };
  18009. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18010. for (var p = 0; p < 6; p++) {
  18011. var inCount = 8;
  18012. for (var i = 0; i < 8; i++) {
  18013. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18014. --inCount;
  18015. }
  18016. else {
  18017. break;
  18018. }
  18019. }
  18020. if (inCount === 0)
  18021. return false;
  18022. }
  18023. return true;
  18024. };
  18025. return BoundingBox;
  18026. }());
  18027. BABYLON.BoundingBox = BoundingBox;
  18028. })(BABYLON || (BABYLON = {}));
  18029. //# sourceMappingURL=babylon.boundingBox.js.map
  18030. var BABYLON;
  18031. (function (BABYLON) {
  18032. var computeBoxExtents = function (axis, box) {
  18033. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18034. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18035. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18036. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18037. var r = r0 + r1 + r2;
  18038. return {
  18039. min: p - r,
  18040. max: p + r
  18041. };
  18042. };
  18043. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18044. var axisOverlap = function (axis, box0, box1) {
  18045. var result0 = computeBoxExtents(axis, box0);
  18046. var result1 = computeBoxExtents(axis, box1);
  18047. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18048. };
  18049. var BoundingInfo = /** @class */ (function () {
  18050. function BoundingInfo(minimum, maximum) {
  18051. this.minimum = minimum;
  18052. this.maximum = maximum;
  18053. this._isLocked = false;
  18054. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18055. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18056. }
  18057. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18058. get: function () {
  18059. return this._isLocked;
  18060. },
  18061. set: function (value) {
  18062. this._isLocked = value;
  18063. },
  18064. enumerable: true,
  18065. configurable: true
  18066. });
  18067. // Methods
  18068. BoundingInfo.prototype.update = function (world) {
  18069. if (this._isLocked) {
  18070. return;
  18071. }
  18072. this.boundingBox._update(world);
  18073. this.boundingSphere._update(world);
  18074. };
  18075. /**
  18076. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18077. * @param center New center of the bounding info
  18078. * @param extend New extend of the bounding info
  18079. */
  18080. BoundingInfo.prototype.centerOn = function (center, extend) {
  18081. this.minimum = center.subtract(extend);
  18082. this.maximum = center.add(extend);
  18083. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18084. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18085. return this;
  18086. };
  18087. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18088. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18089. return false;
  18090. return this.boundingBox.isInFrustum(frustumPlanes);
  18091. };
  18092. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18093. /**
  18094. * Gets the world distance between the min and max points of the bounding box
  18095. */
  18096. get: function () {
  18097. var boundingBox = this.boundingBox;
  18098. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18099. return size.length();
  18100. },
  18101. enumerable: true,
  18102. configurable: true
  18103. });
  18104. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18105. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18106. };
  18107. BoundingInfo.prototype._checkCollision = function (collider) {
  18108. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18109. };
  18110. BoundingInfo.prototype.intersectsPoint = function (point) {
  18111. if (!this.boundingSphere.centerWorld) {
  18112. return false;
  18113. }
  18114. if (!this.boundingSphere.intersectsPoint(point)) {
  18115. return false;
  18116. }
  18117. if (!this.boundingBox.intersectsPoint(point)) {
  18118. return false;
  18119. }
  18120. return true;
  18121. };
  18122. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18123. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18124. return false;
  18125. }
  18126. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18127. return false;
  18128. }
  18129. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18130. return false;
  18131. }
  18132. if (!precise) {
  18133. return true;
  18134. }
  18135. var box0 = this.boundingBox;
  18136. var box1 = boundingInfo.boundingBox;
  18137. if (!axisOverlap(box0.directions[0], box0, box1))
  18138. return false;
  18139. if (!axisOverlap(box0.directions[1], box0, box1))
  18140. return false;
  18141. if (!axisOverlap(box0.directions[2], box0, box1))
  18142. return false;
  18143. if (!axisOverlap(box1.directions[0], box0, box1))
  18144. return false;
  18145. if (!axisOverlap(box1.directions[1], box0, box1))
  18146. return false;
  18147. if (!axisOverlap(box1.directions[2], box0, box1))
  18148. return false;
  18149. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18150. return false;
  18151. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18152. return false;
  18153. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18154. return false;
  18155. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18156. return false;
  18157. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18158. return false;
  18159. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18160. return false;
  18161. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18162. return false;
  18163. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18164. return false;
  18165. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18166. return false;
  18167. return true;
  18168. };
  18169. return BoundingInfo;
  18170. }());
  18171. BABYLON.BoundingInfo = BoundingInfo;
  18172. })(BABYLON || (BABYLON = {}));
  18173. //# sourceMappingURL=babylon.boundingInfo.js.map
  18174. var BABYLON;
  18175. (function (BABYLON) {
  18176. var TransformNode = /** @class */ (function (_super) {
  18177. __extends(TransformNode, _super);
  18178. function TransformNode(name, scene, isPure) {
  18179. if (scene === void 0) { scene = null; }
  18180. if (isPure === void 0) { isPure = true; }
  18181. var _this = _super.call(this, name, scene) || this;
  18182. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18183. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18184. _this._up = new BABYLON.Vector3(0, 1, 0);
  18185. _this._right = new BABYLON.Vector3(1, 0, 0);
  18186. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18187. // Properties
  18188. _this._rotation = BABYLON.Vector3.Zero();
  18189. _this._scaling = BABYLON.Vector3.One();
  18190. _this._isDirty = false;
  18191. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18192. _this.scalingDeterminant = 1;
  18193. _this.infiniteDistance = false;
  18194. _this.position = BABYLON.Vector3.Zero();
  18195. _this._localWorld = BABYLON.Matrix.Zero();
  18196. _this._worldMatrix = BABYLON.Matrix.Zero();
  18197. _this._worldMatrixDeterminant = 0;
  18198. _this._absolutePosition = BABYLON.Vector3.Zero();
  18199. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18200. _this._postMultiplyPivotMatrix = false;
  18201. _this._isWorldMatrixFrozen = false;
  18202. /**
  18203. * An event triggered after the world matrix is updated
  18204. */
  18205. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18206. _this._nonUniformScaling = false;
  18207. if (isPure) {
  18208. _this.getScene().addTransformNode(_this);
  18209. }
  18210. return _this;
  18211. }
  18212. /**
  18213. * Gets a string idenfifying the name of the class
  18214. * @returns "TransformNode" string
  18215. */
  18216. TransformNode.prototype.getClassName = function () {
  18217. return "TransformNode";
  18218. };
  18219. Object.defineProperty(TransformNode.prototype, "rotation", {
  18220. /**
  18221. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18222. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18223. * Default : (0.0, 0.0, 0.0)
  18224. */
  18225. get: function () {
  18226. return this._rotation;
  18227. },
  18228. set: function (newRotation) {
  18229. this._rotation = newRotation;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. Object.defineProperty(TransformNode.prototype, "scaling", {
  18235. /**
  18236. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18237. * Default : (1.0, 1.0, 1.0)
  18238. */
  18239. get: function () {
  18240. return this._scaling;
  18241. },
  18242. /**
  18243. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18244. * Default : (1.0, 1.0, 1.0)
  18245. */
  18246. set: function (newScaling) {
  18247. this._scaling = newScaling;
  18248. },
  18249. enumerable: true,
  18250. configurable: true
  18251. });
  18252. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18253. /**
  18254. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18255. * It's null by default.
  18256. * 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)
  18257. */
  18258. get: function () {
  18259. return this._rotationQuaternion;
  18260. },
  18261. set: function (quaternion) {
  18262. this._rotationQuaternion = quaternion;
  18263. //reset the rotation vector.
  18264. if (quaternion && this.rotation.length()) {
  18265. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18266. }
  18267. },
  18268. enumerable: true,
  18269. configurable: true
  18270. });
  18271. Object.defineProperty(TransformNode.prototype, "forward", {
  18272. /**
  18273. * The forward direction of that transform in world space.
  18274. */
  18275. get: function () {
  18276. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18277. },
  18278. enumerable: true,
  18279. configurable: true
  18280. });
  18281. Object.defineProperty(TransformNode.prototype, "up", {
  18282. /**
  18283. * The up direction of that transform in world space.
  18284. */
  18285. get: function () {
  18286. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18287. },
  18288. enumerable: true,
  18289. configurable: true
  18290. });
  18291. Object.defineProperty(TransformNode.prototype, "right", {
  18292. /**
  18293. * The right direction of that transform in world space.
  18294. */
  18295. get: function () {
  18296. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18297. },
  18298. enumerable: true,
  18299. configurable: true
  18300. });
  18301. /**
  18302. * Returns the latest update of the World matrix
  18303. * Returns a Matrix.
  18304. */
  18305. TransformNode.prototype.getWorldMatrix = function () {
  18306. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18307. this.computeWorldMatrix();
  18308. }
  18309. return this._worldMatrix;
  18310. };
  18311. /**
  18312. * Returns the latest update of the World matrix determinant.
  18313. */
  18314. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18315. return this._worldMatrixDeterminant;
  18316. };
  18317. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18318. /**
  18319. * Returns directly the latest state of the mesh World matrix.
  18320. * A Matrix is returned.
  18321. */
  18322. get: function () {
  18323. return this._worldMatrix;
  18324. },
  18325. enumerable: true,
  18326. configurable: true
  18327. });
  18328. /**
  18329. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18330. * Returns the TransformNode.
  18331. */
  18332. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18333. this._poseMatrix.copyFrom(matrix);
  18334. return this;
  18335. };
  18336. /**
  18337. * Returns the mesh Pose matrix.
  18338. * Returned object : Matrix
  18339. */
  18340. TransformNode.prototype.getPoseMatrix = function () {
  18341. return this._poseMatrix;
  18342. };
  18343. TransformNode.prototype._isSynchronized = function () {
  18344. if (this._isDirty) {
  18345. return false;
  18346. }
  18347. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18348. return false;
  18349. if (this._cache.pivotMatrixUpdated) {
  18350. return false;
  18351. }
  18352. if (this.infiniteDistance) {
  18353. return false;
  18354. }
  18355. if (!this._cache.position.equals(this.position))
  18356. return false;
  18357. if (this.rotationQuaternion) {
  18358. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18359. return false;
  18360. }
  18361. if (!this._cache.rotation.equals(this.rotation))
  18362. return false;
  18363. if (!this._cache.scaling.equals(this.scaling))
  18364. return false;
  18365. return true;
  18366. };
  18367. TransformNode.prototype._initCache = function () {
  18368. _super.prototype._initCache.call(this);
  18369. this._cache.localMatrixUpdated = false;
  18370. this._cache.position = BABYLON.Vector3.Zero();
  18371. this._cache.scaling = BABYLON.Vector3.Zero();
  18372. this._cache.rotation = BABYLON.Vector3.Zero();
  18373. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18374. this._cache.billboardMode = -1;
  18375. };
  18376. TransformNode.prototype.markAsDirty = function (property) {
  18377. if (property === "rotation") {
  18378. this.rotationQuaternion = null;
  18379. }
  18380. this._currentRenderId = Number.MAX_VALUE;
  18381. this._isDirty = true;
  18382. return this;
  18383. };
  18384. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18385. /**
  18386. * Returns the current mesh absolute position.
  18387. * Retuns a Vector3.
  18388. */
  18389. get: function () {
  18390. return this._absolutePosition;
  18391. },
  18392. enumerable: true,
  18393. configurable: true
  18394. });
  18395. /**
  18396. * Sets a new matrix to apply before all other transformation
  18397. * @param matrix defines the transform matrix
  18398. * @returns the current TransformNode
  18399. */
  18400. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18401. return this.setPivotMatrix(matrix, false);
  18402. };
  18403. /**
  18404. * Sets a new pivot matrix to the current node
  18405. * @param matrix defines the new pivot matrix to use
  18406. * @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
  18407. * @returns the current TransformNode
  18408. */
  18409. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18410. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18411. this._pivotMatrix = matrix.clone();
  18412. this._cache.pivotMatrixUpdated = true;
  18413. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18414. if (this._postMultiplyPivotMatrix) {
  18415. if (!this._pivotMatrixInverse) {
  18416. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18417. }
  18418. else {
  18419. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18420. }
  18421. }
  18422. return this;
  18423. };
  18424. /**
  18425. * Returns the mesh pivot matrix.
  18426. * Default : Identity.
  18427. * A Matrix is returned.
  18428. */
  18429. TransformNode.prototype.getPivotMatrix = function () {
  18430. return this._pivotMatrix;
  18431. };
  18432. /**
  18433. * Prevents the World matrix to be computed any longer.
  18434. * Returns the TransformNode.
  18435. */
  18436. TransformNode.prototype.freezeWorldMatrix = function () {
  18437. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18438. this.computeWorldMatrix(true);
  18439. this._isWorldMatrixFrozen = true;
  18440. return this;
  18441. };
  18442. /**
  18443. * Allows back the World matrix computation.
  18444. * Returns the TransformNode.
  18445. */
  18446. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18447. this._isWorldMatrixFrozen = false;
  18448. this.computeWorldMatrix(true);
  18449. return this;
  18450. };
  18451. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18452. /**
  18453. * True if the World matrix has been frozen.
  18454. * Returns a boolean.
  18455. */
  18456. get: function () {
  18457. return this._isWorldMatrixFrozen;
  18458. },
  18459. enumerable: true,
  18460. configurable: true
  18461. });
  18462. /**
  18463. * Retuns the mesh absolute position in the World.
  18464. * Returns a Vector3.
  18465. */
  18466. TransformNode.prototype.getAbsolutePosition = function () {
  18467. this.computeWorldMatrix();
  18468. return this._absolutePosition;
  18469. };
  18470. /**
  18471. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18472. * Returns the TransformNode.
  18473. */
  18474. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18475. if (!absolutePosition) {
  18476. return this;
  18477. }
  18478. var absolutePositionX;
  18479. var absolutePositionY;
  18480. var absolutePositionZ;
  18481. if (absolutePosition.x === undefined) {
  18482. if (arguments.length < 3) {
  18483. return this;
  18484. }
  18485. absolutePositionX = arguments[0];
  18486. absolutePositionY = arguments[1];
  18487. absolutePositionZ = arguments[2];
  18488. }
  18489. else {
  18490. absolutePositionX = absolutePosition.x;
  18491. absolutePositionY = absolutePosition.y;
  18492. absolutePositionZ = absolutePosition.z;
  18493. }
  18494. if (this.parent) {
  18495. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18496. invertParentWorldMatrix.invert();
  18497. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18498. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18499. }
  18500. else {
  18501. this.position.x = absolutePositionX;
  18502. this.position.y = absolutePositionY;
  18503. this.position.z = absolutePositionZ;
  18504. }
  18505. return this;
  18506. };
  18507. /**
  18508. * Sets the mesh position in its local space.
  18509. * Returns the TransformNode.
  18510. */
  18511. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18512. this.computeWorldMatrix();
  18513. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18514. return this;
  18515. };
  18516. /**
  18517. * Returns the mesh position in the local space from the current World matrix values.
  18518. * Returns a new Vector3.
  18519. */
  18520. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18521. this.computeWorldMatrix();
  18522. var invLocalWorldMatrix = this._localWorld.clone();
  18523. invLocalWorldMatrix.invert();
  18524. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18525. };
  18526. /**
  18527. * Translates the mesh along the passed Vector3 in its local space.
  18528. * Returns the TransformNode.
  18529. */
  18530. TransformNode.prototype.locallyTranslate = function (vector3) {
  18531. this.computeWorldMatrix(true);
  18532. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18533. return this;
  18534. };
  18535. /**
  18536. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18537. * @param targetPoint the position (must be in same space as current mesh) to look at
  18538. * @param yawCor optional yaw (y-axis) correction in radians
  18539. * @param pitchCor optional pitch (x-axis) correction in radians
  18540. * @param rollCor optional roll (z-axis) correction in radians
  18541. * @param space the choosen space of the target
  18542. * @returns the TransformNode.
  18543. */
  18544. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18545. if (yawCor === void 0) { yawCor = 0; }
  18546. if (pitchCor === void 0) { pitchCor = 0; }
  18547. if (rollCor === void 0) { rollCor = 0; }
  18548. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18549. var dv = TransformNode._lookAtVectorCache;
  18550. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18551. targetPoint.subtractToRef(pos, dv);
  18552. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18553. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18554. var pitch = Math.atan2(dv.y, len);
  18555. if (this.rotationQuaternion) {
  18556. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18557. }
  18558. else {
  18559. this.rotation.x = pitch + pitchCor;
  18560. this.rotation.y = yaw + yawCor;
  18561. this.rotation.z = rollCor;
  18562. }
  18563. return this;
  18564. };
  18565. /**
  18566. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18567. * This Vector3 is expressed in the World space.
  18568. */
  18569. TransformNode.prototype.getDirection = function (localAxis) {
  18570. var result = BABYLON.Vector3.Zero();
  18571. this.getDirectionToRef(localAxis, result);
  18572. return result;
  18573. };
  18574. /**
  18575. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18576. * localAxis is expressed in the mesh local space.
  18577. * result is computed in the Wordl space from the mesh World matrix.
  18578. * Returns the TransformNode.
  18579. */
  18580. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18581. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18582. return this;
  18583. };
  18584. /**
  18585. * Sets a new pivot point to the current node
  18586. * @param point defines the new pivot point to use
  18587. * @param space defines if the point is in world or local space (local by default)
  18588. * @returns the current TransformNode
  18589. */
  18590. TransformNode.prototype.setPivotPoint = function (point, space) {
  18591. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18592. if (this.getScene().getRenderId() == 0) {
  18593. this.computeWorldMatrix(true);
  18594. }
  18595. var wm = this.getWorldMatrix();
  18596. if (space == BABYLON.Space.WORLD) {
  18597. var tmat = BABYLON.Tmp.Matrix[0];
  18598. wm.invertToRef(tmat);
  18599. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18600. }
  18601. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18602. };
  18603. /**
  18604. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18605. */
  18606. TransformNode.prototype.getPivotPoint = function () {
  18607. var point = BABYLON.Vector3.Zero();
  18608. this.getPivotPointToRef(point);
  18609. return point;
  18610. };
  18611. /**
  18612. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18613. * Returns the TransformNode.
  18614. */
  18615. TransformNode.prototype.getPivotPointToRef = function (result) {
  18616. result.x = -this._pivotMatrix.m[12];
  18617. result.y = -this._pivotMatrix.m[13];
  18618. result.z = -this._pivotMatrix.m[14];
  18619. return this;
  18620. };
  18621. /**
  18622. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18623. */
  18624. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18625. var point = BABYLON.Vector3.Zero();
  18626. this.getAbsolutePivotPointToRef(point);
  18627. return point;
  18628. };
  18629. /**
  18630. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18631. * Returns the TransformNode.
  18632. */
  18633. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18634. result.x = this._pivotMatrix.m[12];
  18635. result.y = this._pivotMatrix.m[13];
  18636. result.z = this._pivotMatrix.m[14];
  18637. this.getPivotPointToRef(result);
  18638. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18639. return this;
  18640. };
  18641. /**
  18642. * Defines the passed node as the parent of the current node.
  18643. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18644. * Returns the TransformNode.
  18645. */
  18646. TransformNode.prototype.setParent = function (node) {
  18647. if (node === null) {
  18648. var rotation = BABYLON.Tmp.Quaternion[0];
  18649. var position = BABYLON.Tmp.Vector3[0];
  18650. var scale = BABYLON.Tmp.Vector3[1];
  18651. if (this.parent && this.parent.computeWorldMatrix) {
  18652. this.parent.computeWorldMatrix(true);
  18653. }
  18654. this.computeWorldMatrix(true);
  18655. this.getWorldMatrix().decompose(scale, rotation, position);
  18656. if (this.rotationQuaternion) {
  18657. this.rotationQuaternion.copyFrom(rotation);
  18658. }
  18659. else {
  18660. rotation.toEulerAnglesToRef(this.rotation);
  18661. }
  18662. this.scaling.x = scale.x;
  18663. this.scaling.y = scale.y;
  18664. this.scaling.z = scale.z;
  18665. this.position.x = position.x;
  18666. this.position.y = position.y;
  18667. this.position.z = position.z;
  18668. }
  18669. else {
  18670. var rotation = BABYLON.Tmp.Quaternion[0];
  18671. var position = BABYLON.Tmp.Vector3[0];
  18672. var scale = BABYLON.Tmp.Vector3[1];
  18673. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18674. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18675. this.computeWorldMatrix(true);
  18676. node.computeWorldMatrix(true);
  18677. node.getWorldMatrix().invertToRef(invParentMatrix);
  18678. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18679. diffMatrix.decompose(scale, rotation, position);
  18680. if (this.rotationQuaternion) {
  18681. this.rotationQuaternion.copyFrom(rotation);
  18682. }
  18683. else {
  18684. rotation.toEulerAnglesToRef(this.rotation);
  18685. }
  18686. this.position.x = position.x;
  18687. this.position.y = position.y;
  18688. this.position.z = position.z;
  18689. this.scaling.x = scale.x;
  18690. this.scaling.y = scale.y;
  18691. this.scaling.z = scale.z;
  18692. }
  18693. this.parent = node;
  18694. return this;
  18695. };
  18696. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18697. get: function () {
  18698. return this._nonUniformScaling;
  18699. },
  18700. enumerable: true,
  18701. configurable: true
  18702. });
  18703. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18704. if (this._nonUniformScaling === value) {
  18705. return false;
  18706. }
  18707. this._nonUniformScaling = true;
  18708. return true;
  18709. };
  18710. /**
  18711. * Attach the current TransformNode to another TransformNode associated with a bone
  18712. * @param bone Bone affecting the TransformNode
  18713. * @param affectedTransformNode TransformNode associated with the bone
  18714. */
  18715. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18716. this._transformToBoneReferal = affectedTransformNode;
  18717. this.parent = bone;
  18718. if (bone.getWorldMatrix().determinant() < 0) {
  18719. this.scalingDeterminant *= -1;
  18720. }
  18721. return this;
  18722. };
  18723. TransformNode.prototype.detachFromBone = function () {
  18724. if (!this.parent) {
  18725. return this;
  18726. }
  18727. if (this.parent.getWorldMatrix().determinant() < 0) {
  18728. this.scalingDeterminant *= -1;
  18729. }
  18730. this._transformToBoneReferal = null;
  18731. this.parent = null;
  18732. return this;
  18733. };
  18734. /**
  18735. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18736. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18737. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18738. * The passed axis is also normalized.
  18739. * Returns the TransformNode.
  18740. */
  18741. TransformNode.prototype.rotate = function (axis, amount, space) {
  18742. axis.normalize();
  18743. if (!this.rotationQuaternion) {
  18744. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18745. this.rotation = BABYLON.Vector3.Zero();
  18746. }
  18747. var rotationQuaternion;
  18748. if (!space || space === BABYLON.Space.LOCAL) {
  18749. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18750. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18751. }
  18752. else {
  18753. if (this.parent) {
  18754. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18755. invertParentWorldMatrix.invert();
  18756. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18757. }
  18758. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18759. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18760. }
  18761. return this;
  18762. };
  18763. /**
  18764. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18765. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18766. * The passed axis is also normalized.
  18767. * Returns the TransformNode.
  18768. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18769. */
  18770. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18771. axis.normalize();
  18772. if (!this.rotationQuaternion) {
  18773. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18774. this.rotation.copyFromFloats(0, 0, 0);
  18775. }
  18776. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18777. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18778. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18779. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18780. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18781. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18782. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18783. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18784. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18785. return this;
  18786. };
  18787. /**
  18788. * Translates the mesh along the axis vector for the passed distance in the given space.
  18789. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18790. * Returns the TransformNode.
  18791. */
  18792. TransformNode.prototype.translate = function (axis, distance, space) {
  18793. var displacementVector = axis.scale(distance);
  18794. if (!space || space === BABYLON.Space.LOCAL) {
  18795. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18796. this.setPositionWithLocalVector(tempV3);
  18797. }
  18798. else {
  18799. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18800. }
  18801. return this;
  18802. };
  18803. /**
  18804. * Adds a rotation step to the mesh current rotation.
  18805. * x, y, z are Euler angles expressed in radians.
  18806. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18807. * This means this rotation is made in the mesh local space only.
  18808. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18809. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18810. * ```javascript
  18811. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18812. * ```
  18813. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18814. * 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.
  18815. * Returns the TransformNode.
  18816. */
  18817. TransformNode.prototype.addRotation = function (x, y, z) {
  18818. var rotationQuaternion;
  18819. if (this.rotationQuaternion) {
  18820. rotationQuaternion = this.rotationQuaternion;
  18821. }
  18822. else {
  18823. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18824. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18825. }
  18826. var accumulation = BABYLON.Tmp.Quaternion[0];
  18827. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18828. rotationQuaternion.multiplyInPlace(accumulation);
  18829. if (!this.rotationQuaternion) {
  18830. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18831. }
  18832. return this;
  18833. };
  18834. /**
  18835. * Computes the mesh World matrix and returns it.
  18836. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18837. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18838. * If the parameter `force`is set to `true`, the actual computation is done.
  18839. * Returns the mesh World Matrix.
  18840. */
  18841. TransformNode.prototype.computeWorldMatrix = function (force) {
  18842. if (this._isWorldMatrixFrozen) {
  18843. return this._worldMatrix;
  18844. }
  18845. if (!force && this.isSynchronized(true)) {
  18846. this._currentRenderId = this.getScene().getRenderId();
  18847. return this._worldMatrix;
  18848. }
  18849. this._cache.position.copyFrom(this.position);
  18850. this._cache.scaling.copyFrom(this.scaling);
  18851. this._cache.pivotMatrixUpdated = false;
  18852. this._cache.billboardMode = this.billboardMode;
  18853. this._currentRenderId = this.getScene().getRenderId();
  18854. this._childRenderId = this.getScene().getRenderId();
  18855. this._isDirty = false;
  18856. // Scaling
  18857. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18858. // Rotation
  18859. //rotate, if quaternion is set and rotation was used
  18860. if (this.rotationQuaternion) {
  18861. var len = this.rotation.length();
  18862. if (len) {
  18863. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18864. this.rotation.copyFromFloats(0, 0, 0);
  18865. }
  18866. }
  18867. if (this.rotationQuaternion) {
  18868. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18869. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18870. }
  18871. else {
  18872. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18873. this._cache.rotation.copyFrom(this.rotation);
  18874. }
  18875. // Translation
  18876. var camera = this.getScene().activeCamera;
  18877. if (this.infiniteDistance && !this.parent && camera) {
  18878. var cameraWorldMatrix = camera.getWorldMatrix();
  18879. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18880. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18881. }
  18882. else {
  18883. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18884. }
  18885. // Composing transformations
  18886. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18887. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18888. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18889. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18890. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18891. // Need to decompose each rotation here
  18892. var currentPosition = BABYLON.Tmp.Vector3[3];
  18893. if (this.parent && this.parent.getWorldMatrix) {
  18894. if (this._transformToBoneReferal) {
  18895. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18896. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18897. }
  18898. else {
  18899. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18900. }
  18901. }
  18902. else {
  18903. currentPosition.copyFrom(this.position);
  18904. }
  18905. currentPosition.subtractInPlace(camera.globalPosition);
  18906. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18907. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18908. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18909. }
  18910. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18911. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18912. }
  18913. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18914. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18915. }
  18916. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18917. }
  18918. else {
  18919. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18920. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18921. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18922. }
  18923. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18924. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18925. }
  18926. // Local world
  18927. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18928. // Parent
  18929. if (this.parent && this.parent.getWorldMatrix) {
  18930. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18931. if (this._transformToBoneReferal) {
  18932. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18933. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18934. }
  18935. else {
  18936. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18937. }
  18938. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18939. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18940. this._worldMatrix.copyFrom(this._localWorld);
  18941. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18942. }
  18943. else {
  18944. if (this._transformToBoneReferal) {
  18945. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18946. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18947. }
  18948. else {
  18949. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18950. }
  18951. }
  18952. this._markSyncedWithParent();
  18953. }
  18954. else {
  18955. this._worldMatrix.copyFrom(this._localWorld);
  18956. }
  18957. // Post multiply inverse of pivotMatrix
  18958. if (this._postMultiplyPivotMatrix) {
  18959. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18960. }
  18961. // Normal matrix
  18962. if (this.scaling.isNonUniform) {
  18963. this._updateNonUniformScalingState(true);
  18964. }
  18965. else if (this.parent && this.parent._nonUniformScaling) {
  18966. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18967. }
  18968. else {
  18969. this._updateNonUniformScalingState(false);
  18970. }
  18971. this._afterComputeWorldMatrix();
  18972. // Absolute position
  18973. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18974. // Callbacks
  18975. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18976. if (!this._poseMatrix) {
  18977. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18978. }
  18979. // Cache the determinant
  18980. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18981. return this._worldMatrix;
  18982. };
  18983. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18984. };
  18985. /**
  18986. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18987. * @param func: callback function to add
  18988. *
  18989. * Returns the TransformNode.
  18990. */
  18991. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18992. this.onAfterWorldMatrixUpdateObservable.add(func);
  18993. return this;
  18994. };
  18995. /**
  18996. * Removes a registered callback function.
  18997. * Returns the TransformNode.
  18998. */
  18999. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19000. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19001. return this;
  19002. };
  19003. /**
  19004. * Clone the current transform node
  19005. * Returns the new transform node
  19006. * @param name Name of the new clone
  19007. * @param newParent New parent for the clone
  19008. * @param doNotCloneChildren Do not clone children hierarchy
  19009. */
  19010. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19011. var _this = this;
  19012. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19013. result.name = name;
  19014. result.id = name;
  19015. if (newParent) {
  19016. result.parent = newParent;
  19017. }
  19018. if (!doNotCloneChildren) {
  19019. // Children
  19020. var directDescendants = this.getDescendants(true);
  19021. for (var index = 0; index < directDescendants.length; index++) {
  19022. var child = directDescendants[index];
  19023. if (child.clone) {
  19024. child.clone(name + "." + child.name, result);
  19025. }
  19026. }
  19027. }
  19028. return result;
  19029. };
  19030. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19031. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19032. serializationObject.type = this.getClassName();
  19033. // Parent
  19034. if (this.parent) {
  19035. serializationObject.parentId = this.parent.id;
  19036. }
  19037. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19038. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19039. }
  19040. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19041. serializationObject.isEnabled = this.isEnabled();
  19042. // Parent
  19043. if (this.parent) {
  19044. serializationObject.parentId = this.parent.id;
  19045. }
  19046. return serializationObject;
  19047. };
  19048. // Statics
  19049. /**
  19050. * Returns a new TransformNode object parsed from the source provided.
  19051. * The parameter `parsedMesh` is the source.
  19052. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19053. */
  19054. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19055. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19056. if (BABYLON.Tags) {
  19057. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19058. }
  19059. if (parsedTransformNode.localMatrix) {
  19060. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19061. }
  19062. else if (parsedTransformNode.pivotMatrix) {
  19063. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19064. }
  19065. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19066. // Parent
  19067. if (parsedTransformNode.parentId) {
  19068. transformNode._waitingParentId = parsedTransformNode.parentId;
  19069. }
  19070. return transformNode;
  19071. };
  19072. /**
  19073. * Releases resources associated with this transform node.
  19074. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19075. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19076. */
  19077. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19078. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19079. // Animations
  19080. this.getScene().stopAnimation(this);
  19081. // Remove from scene
  19082. this.getScene().removeTransformNode(this);
  19083. this.onAfterWorldMatrixUpdateObservable.clear();
  19084. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19085. };
  19086. // Statics
  19087. TransformNode.BILLBOARDMODE_NONE = 0;
  19088. TransformNode.BILLBOARDMODE_X = 1;
  19089. TransformNode.BILLBOARDMODE_Y = 2;
  19090. TransformNode.BILLBOARDMODE_Z = 4;
  19091. TransformNode.BILLBOARDMODE_ALL = 7;
  19092. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19093. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19094. __decorate([
  19095. BABYLON.serializeAsVector3()
  19096. ], TransformNode.prototype, "_rotation", void 0);
  19097. __decorate([
  19098. BABYLON.serializeAsQuaternion()
  19099. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19100. __decorate([
  19101. BABYLON.serializeAsVector3()
  19102. ], TransformNode.prototype, "_scaling", void 0);
  19103. __decorate([
  19104. BABYLON.serialize()
  19105. ], TransformNode.prototype, "billboardMode", void 0);
  19106. __decorate([
  19107. BABYLON.serialize()
  19108. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19109. __decorate([
  19110. BABYLON.serialize()
  19111. ], TransformNode.prototype, "infiniteDistance", void 0);
  19112. __decorate([
  19113. BABYLON.serializeAsVector3()
  19114. ], TransformNode.prototype, "position", void 0);
  19115. return TransformNode;
  19116. }(BABYLON.Node));
  19117. BABYLON.TransformNode = TransformNode;
  19118. })(BABYLON || (BABYLON = {}));
  19119. //# sourceMappingURL=babylon.transformNode.js.map
  19120. var BABYLON;
  19121. (function (BABYLON) {
  19122. var AbstractMesh = /** @class */ (function (_super) {
  19123. __extends(AbstractMesh, _super);
  19124. // Constructor
  19125. function AbstractMesh(name, scene) {
  19126. if (scene === void 0) { scene = null; }
  19127. var _this = _super.call(this, name, scene, false) || this;
  19128. _this._facetNb = 0; // facet number
  19129. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19130. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19131. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19132. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19133. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19134. _this._subDiv = {
  19135. max: 1,
  19136. X: 1,
  19137. Y: 1,
  19138. Z: 1
  19139. };
  19140. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19141. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19142. // Events
  19143. /**
  19144. * An event triggered when this mesh collides with another one
  19145. */
  19146. _this.onCollideObservable = new BABYLON.Observable();
  19147. /**
  19148. * An event triggered when the collision's position changes
  19149. */
  19150. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19151. /**
  19152. * An event triggered when material is changed
  19153. */
  19154. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19155. // Properties
  19156. _this.definedFacingForward = true; // orientation for POV movement & rotation
  19157. /**
  19158. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19159. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19160. * or
  19161. * 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.
  19162. * for more info check WebGl documentations
  19163. */
  19164. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19165. /**
  19166. * 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:
  19167. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19168. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19169. * 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.
  19170. */
  19171. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19172. /**
  19173. * 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.
  19174. * The default value is -1 which means don't break the query and wait till the result.
  19175. */
  19176. _this.occlusionRetryCount = -1;
  19177. _this._occlusionInternalRetryCounter = 0;
  19178. _this._isOccluded = false;
  19179. _this._isOcclusionQueryInProgress = false;
  19180. _this._visibility = 1.0;
  19181. _this.alphaIndex = Number.MAX_VALUE;
  19182. _this.isVisible = true;
  19183. _this.isPickable = true;
  19184. _this.showBoundingBox = false;
  19185. _this.showSubMeshesBoundingBox = false;
  19186. _this.isBlocker = false;
  19187. _this.enablePointerMoveEvents = false;
  19188. _this.renderingGroupId = 0;
  19189. _this._receiveShadows = false;
  19190. _this.renderOutline = false;
  19191. _this.outlineColor = BABYLON.Color3.Red();
  19192. _this.outlineWidth = 0.02;
  19193. _this.renderOverlay = false;
  19194. _this.overlayColor = BABYLON.Color3.Red();
  19195. _this.overlayAlpha = 0.5;
  19196. _this._hasVertexAlpha = false;
  19197. _this._useVertexColors = true;
  19198. _this._computeBonesUsingShaders = true;
  19199. _this._numBoneInfluencers = 4;
  19200. _this._applyFog = true;
  19201. _this.useOctreeForRenderingSelection = true;
  19202. _this.useOctreeForPicking = true;
  19203. _this.useOctreeForCollisions = true;
  19204. _this._layerMask = 0x0FFFFFFF;
  19205. /**
  19206. * True if the mesh must be rendered in any case.
  19207. */
  19208. _this.alwaysSelectAsActiveMesh = false;
  19209. /**
  19210. * This scene's action manager
  19211. */
  19212. _this.actionManager = null;
  19213. // Physics
  19214. _this.physicsImpostor = null;
  19215. // Collisions
  19216. _this._checkCollisions = false;
  19217. _this._collisionMask = -1;
  19218. _this._collisionGroup = -1;
  19219. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19220. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19221. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19222. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19223. // Edges
  19224. _this.edgesWidth = 1;
  19225. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19226. // Cache
  19227. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19228. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19229. _this._renderId = 0;
  19230. _this._intersectionsInProgress = new Array();
  19231. _this._unIndexed = false;
  19232. _this._lightSources = new Array();
  19233. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19234. if (collidedMesh === void 0) { collidedMesh = null; }
  19235. //TODO move this to the collision coordinator!
  19236. if (_this.getScene().workerCollisions)
  19237. newPosition.multiplyInPlace(_this._collider._radius);
  19238. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19239. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19240. _this.position.addInPlace(_this._diffPositionForCollisions);
  19241. }
  19242. if (collidedMesh) {
  19243. _this.onCollideObservable.notifyObservers(collidedMesh);
  19244. }
  19245. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19246. };
  19247. _this.getScene().addMesh(_this);
  19248. _this._resyncLightSources();
  19249. return _this;
  19250. }
  19251. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19252. get: function () {
  19253. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19259. get: function () {
  19260. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19266. get: function () {
  19267. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19268. },
  19269. enumerable: true,
  19270. configurable: true
  19271. });
  19272. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19273. get: function () {
  19274. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19280. get: function () {
  19281. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19282. },
  19283. enumerable: true,
  19284. configurable: true
  19285. });
  19286. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19287. /**
  19288. * Read-only : the number of facets in the mesh
  19289. */
  19290. get: function () {
  19291. return this._facetNb;
  19292. },
  19293. enumerable: true,
  19294. configurable: true
  19295. });
  19296. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19297. /**
  19298. * The number (integer) of subdivisions per axis in the partioning space
  19299. */
  19300. get: function () {
  19301. return this._partitioningSubdivisions;
  19302. },
  19303. set: function (nb) {
  19304. this._partitioningSubdivisions = nb;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19310. /**
  19311. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19312. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  19313. */
  19314. get: function () {
  19315. return this._partitioningBBoxRatio;
  19316. },
  19317. set: function (ratio) {
  19318. this._partitioningBBoxRatio = ratio;
  19319. },
  19320. enumerable: true,
  19321. configurable: true
  19322. });
  19323. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19324. /**
  19325. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  19326. * Works only for updatable meshes.
  19327. * Doesn't work with multi-materials.
  19328. */
  19329. get: function () {
  19330. return this._facetDepthSort;
  19331. },
  19332. set: function (sort) {
  19333. this._facetDepthSort = sort;
  19334. },
  19335. enumerable: true,
  19336. configurable: true
  19337. });
  19338. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19339. /**
  19340. * The location (Vector3) where the facet depth sort must be computed from.
  19341. * By default, the active camera position.
  19342. * Used only when facet depth sort is enabled.
  19343. */
  19344. get: function () {
  19345. return this._facetDepthSortFrom;
  19346. },
  19347. set: function (location) {
  19348. this._facetDepthSortFrom = location;
  19349. },
  19350. enumerable: true,
  19351. configurable: true
  19352. });
  19353. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19354. /**
  19355. * Read-only boolean : is the feature facetData enabled ?
  19356. */
  19357. get: function () {
  19358. return this._facetDataEnabled;
  19359. },
  19360. enumerable: true,
  19361. configurable: true
  19362. });
  19363. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19364. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19365. return false;
  19366. }
  19367. this._markSubMeshesAsMiscDirty();
  19368. return true;
  19369. };
  19370. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19371. set: function (callback) {
  19372. if (this._onCollideObserver) {
  19373. this.onCollideObservable.remove(this._onCollideObserver);
  19374. }
  19375. this._onCollideObserver = this.onCollideObservable.add(callback);
  19376. },
  19377. enumerable: true,
  19378. configurable: true
  19379. });
  19380. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19381. set: function (callback) {
  19382. if (this._onCollisionPositionChangeObserver) {
  19383. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19384. }
  19385. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19386. },
  19387. enumerable: true,
  19388. configurable: true
  19389. });
  19390. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19391. /**
  19392. * 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.
  19393. */
  19394. get: function () {
  19395. return this._isOccluded;
  19396. },
  19397. set: function (value) {
  19398. this._isOccluded = value;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19404. /**
  19405. * Flag to check the progress status of the query
  19406. */
  19407. get: function () {
  19408. return this._isOcclusionQueryInProgress;
  19409. },
  19410. enumerable: true,
  19411. configurable: true
  19412. });
  19413. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19414. /**
  19415. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19416. */
  19417. get: function () {
  19418. return this._visibility;
  19419. },
  19420. /**
  19421. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  19422. */
  19423. set: function (value) {
  19424. if (this._visibility === value) {
  19425. return;
  19426. }
  19427. this._visibility = value;
  19428. this._markSubMeshesAsMiscDirty();
  19429. },
  19430. enumerable: true,
  19431. configurable: true
  19432. });
  19433. Object.defineProperty(AbstractMesh.prototype, "material", {
  19434. get: function () {
  19435. return this._material;
  19436. },
  19437. set: function (value) {
  19438. if (this._material === value) {
  19439. return;
  19440. }
  19441. this._material = value;
  19442. if (this.onMaterialChangedObservable.hasObservers) {
  19443. this.onMaterialChangedObservable.notifyObservers(this);
  19444. }
  19445. if (!this.subMeshes) {
  19446. return;
  19447. }
  19448. this._unBindEffect();
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19454. get: function () {
  19455. return this._receiveShadows;
  19456. },
  19457. set: function (value) {
  19458. if (this._receiveShadows === value) {
  19459. return;
  19460. }
  19461. this._receiveShadows = value;
  19462. this._markSubMeshesAsLightDirty();
  19463. },
  19464. enumerable: true,
  19465. configurable: true
  19466. });
  19467. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19468. get: function () {
  19469. return this._hasVertexAlpha;
  19470. },
  19471. set: function (value) {
  19472. if (this._hasVertexAlpha === value) {
  19473. return;
  19474. }
  19475. this._hasVertexAlpha = value;
  19476. this._markSubMeshesAsAttributesDirty();
  19477. this._markSubMeshesAsMiscDirty();
  19478. },
  19479. enumerable: true,
  19480. configurable: true
  19481. });
  19482. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19483. get: function () {
  19484. return this._useVertexColors;
  19485. },
  19486. set: function (value) {
  19487. if (this._useVertexColors === value) {
  19488. return;
  19489. }
  19490. this._useVertexColors = value;
  19491. this._markSubMeshesAsAttributesDirty();
  19492. },
  19493. enumerable: true,
  19494. configurable: true
  19495. });
  19496. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19497. get: function () {
  19498. return this._computeBonesUsingShaders;
  19499. },
  19500. set: function (value) {
  19501. if (this._computeBonesUsingShaders === value) {
  19502. return;
  19503. }
  19504. this._computeBonesUsingShaders = value;
  19505. this._markSubMeshesAsAttributesDirty();
  19506. },
  19507. enumerable: true,
  19508. configurable: true
  19509. });
  19510. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19511. get: function () {
  19512. return this._numBoneInfluencers;
  19513. },
  19514. set: function (value) {
  19515. if (this._numBoneInfluencers === value) {
  19516. return;
  19517. }
  19518. this._numBoneInfluencers = value;
  19519. this._markSubMeshesAsAttributesDirty();
  19520. },
  19521. enumerable: true,
  19522. configurable: true
  19523. });
  19524. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19525. get: function () {
  19526. return this._applyFog;
  19527. },
  19528. set: function (value) {
  19529. if (this._applyFog === value) {
  19530. return;
  19531. }
  19532. this._applyFog = value;
  19533. this._markSubMeshesAsMiscDirty();
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19539. get: function () {
  19540. return this._layerMask;
  19541. },
  19542. set: function (value) {
  19543. if (value === this._layerMask) {
  19544. return;
  19545. }
  19546. this._layerMask = value;
  19547. this._resyncLightSources();
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19553. get: function () {
  19554. return this._collisionMask;
  19555. },
  19556. set: function (mask) {
  19557. this._collisionMask = !isNaN(mask) ? mask : -1;
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19563. get: function () {
  19564. return this._collisionGroup;
  19565. },
  19566. set: function (mask) {
  19567. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19573. get: function () {
  19574. return null;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19580. get: function () {
  19581. return this._skeleton;
  19582. },
  19583. set: function (value) {
  19584. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19585. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19586. }
  19587. if (value && value.needInitialSkinMatrix) {
  19588. value._registerMeshWithPoseMatrix(this);
  19589. }
  19590. this._skeleton = value;
  19591. if (!this._skeleton) {
  19592. this._bonesTransformMatrices = null;
  19593. }
  19594. this._markSubMeshesAsAttributesDirty();
  19595. },
  19596. enumerable: true,
  19597. configurable: true
  19598. });
  19599. /**
  19600. * Returns the string "AbstractMesh"
  19601. */
  19602. AbstractMesh.prototype.getClassName = function () {
  19603. return "AbstractMesh";
  19604. };
  19605. /**
  19606. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19607. */
  19608. AbstractMesh.prototype.toString = function (fullDetails) {
  19609. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19610. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19611. if (this._skeleton) {
  19612. ret += ", skeleton: " + this._skeleton.name;
  19613. }
  19614. if (fullDetails) {
  19615. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19616. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19617. }
  19618. return ret;
  19619. };
  19620. AbstractMesh.prototype._rebuild = function () {
  19621. if (this._occlusionQuery) {
  19622. this._occlusionQuery = null;
  19623. }
  19624. if (this._edgesRenderer) {
  19625. this._edgesRenderer._rebuild();
  19626. }
  19627. if (!this.subMeshes) {
  19628. return;
  19629. }
  19630. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19631. var subMesh = _a[_i];
  19632. subMesh._rebuild();
  19633. }
  19634. };
  19635. AbstractMesh.prototype._resyncLightSources = function () {
  19636. this._lightSources.length = 0;
  19637. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19638. var light = _a[_i];
  19639. if (!light.isEnabled()) {
  19640. continue;
  19641. }
  19642. if (light.canAffectMesh(this)) {
  19643. this._lightSources.push(light);
  19644. }
  19645. }
  19646. this._markSubMeshesAsLightDirty();
  19647. };
  19648. AbstractMesh.prototype._resyncLighSource = function (light) {
  19649. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19650. var index = this._lightSources.indexOf(light);
  19651. if (index === -1) {
  19652. if (!isIn) {
  19653. return;
  19654. }
  19655. this._lightSources.push(light);
  19656. }
  19657. else {
  19658. if (isIn) {
  19659. return;
  19660. }
  19661. this._lightSources.splice(index, 1);
  19662. }
  19663. this._markSubMeshesAsLightDirty();
  19664. };
  19665. /** @ignore */
  19666. AbstractMesh.prototype._unBindEffect = function () {
  19667. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19668. var subMesh = _a[_i];
  19669. subMesh.setEffect(null);
  19670. }
  19671. };
  19672. AbstractMesh.prototype._removeLightSource = function (light) {
  19673. var index = this._lightSources.indexOf(light);
  19674. if (index === -1) {
  19675. return;
  19676. }
  19677. this._lightSources.splice(index, 1);
  19678. this._markSubMeshesAsLightDirty();
  19679. };
  19680. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19681. if (!this.subMeshes) {
  19682. return;
  19683. }
  19684. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19685. var subMesh = _a[_i];
  19686. if (subMesh._materialDefines) {
  19687. func(subMesh._materialDefines);
  19688. }
  19689. }
  19690. };
  19691. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19692. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19693. };
  19694. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19695. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19696. };
  19697. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19698. if (!this.subMeshes) {
  19699. return;
  19700. }
  19701. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19702. var subMesh = _a[_i];
  19703. var material = subMesh.getMaterial();
  19704. if (material) {
  19705. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19706. }
  19707. }
  19708. };
  19709. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19710. /**
  19711. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19712. * Default : (1.0, 1.0, 1.0)
  19713. */
  19714. get: function () {
  19715. return this._scaling;
  19716. },
  19717. /**
  19718. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  19719. * Default : (1.0, 1.0, 1.0)
  19720. */
  19721. set: function (newScaling) {
  19722. this._scaling = newScaling;
  19723. if (this.physicsImpostor) {
  19724. this.physicsImpostor.forceUpdate();
  19725. }
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. // Methods
  19731. /**
  19732. * Disables the mesh edger rendering mode.
  19733. * Returns the AbstractMesh.
  19734. */
  19735. AbstractMesh.prototype.disableEdgesRendering = function () {
  19736. if (this._edgesRenderer) {
  19737. this._edgesRenderer.dispose();
  19738. this._edgesRenderer = null;
  19739. }
  19740. return this;
  19741. };
  19742. /**
  19743. * Enables the edge rendering mode on the mesh.
  19744. * This mode makes the mesh edges visible.
  19745. * Returns the AbstractMesh.
  19746. */
  19747. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19748. if (epsilon === void 0) { epsilon = 0.95; }
  19749. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19750. this.disableEdgesRendering();
  19751. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19752. return this;
  19753. };
  19754. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19755. /**
  19756. * Returns true if the mesh is blocked. Used by the class Mesh.
  19757. * Returns the boolean `false` by default.
  19758. */
  19759. get: function () {
  19760. return false;
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. /**
  19766. * Returns the mesh itself by default, used by the class Mesh.
  19767. * Returned type : AbstractMesh
  19768. */
  19769. AbstractMesh.prototype.getLOD = function (camera) {
  19770. return this;
  19771. };
  19772. /**
  19773. * Returns 0 by default, used by the class Mesh.
  19774. * Returns an integer.
  19775. */
  19776. AbstractMesh.prototype.getTotalVertices = function () {
  19777. return 0;
  19778. };
  19779. /**
  19780. * Returns null by default, used by the class Mesh.
  19781. * Returned type : integer array
  19782. */
  19783. AbstractMesh.prototype.getIndices = function () {
  19784. return null;
  19785. };
  19786. /**
  19787. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  19788. * Returned type : float array or Float32Array
  19789. */
  19790. AbstractMesh.prototype.getVerticesData = function (kind) {
  19791. return null;
  19792. };
  19793. /**
  19794. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19795. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19796. * The `data` are either a numeric array either a Float32Array.
  19797. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19798. * 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).
  19799. * Note that a new underlying VertexBuffer object is created each call.
  19800. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19801. *
  19802. * Possible `kind` values :
  19803. * - BABYLON.VertexBuffer.PositionKind
  19804. * - BABYLON.VertexBuffer.UVKind
  19805. * - BABYLON.VertexBuffer.UV2Kind
  19806. * - BABYLON.VertexBuffer.UV3Kind
  19807. * - BABYLON.VertexBuffer.UV4Kind
  19808. * - BABYLON.VertexBuffer.UV5Kind
  19809. * - BABYLON.VertexBuffer.UV6Kind
  19810. * - BABYLON.VertexBuffer.ColorKind
  19811. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19812. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19813. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19814. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19815. *
  19816. * Returns the Mesh.
  19817. */
  19818. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19819. return this;
  19820. };
  19821. /**
  19822. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19823. * If the mesh has no geometry, it is simply returned as it is.
  19824. * The `data` are either a numeric array either a Float32Array.
  19825. * No new underlying VertexBuffer object is created.
  19826. * 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.
  19827. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19828. *
  19829. * Possible `kind` values :
  19830. * - BABYLON.VertexBuffer.PositionKind
  19831. * - BABYLON.VertexBuffer.UVKind
  19832. * - BABYLON.VertexBuffer.UV2Kind
  19833. * - BABYLON.VertexBuffer.UV3Kind
  19834. * - BABYLON.VertexBuffer.UV4Kind
  19835. * - BABYLON.VertexBuffer.UV5Kind
  19836. * - BABYLON.VertexBuffer.UV6Kind
  19837. * - BABYLON.VertexBuffer.ColorKind
  19838. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19839. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19840. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19841. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19842. *
  19843. * Returns the Mesh.
  19844. */
  19845. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19846. return this;
  19847. };
  19848. /**
  19849. * Sets the mesh indices.
  19850. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  19851. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19852. * This method creates a new index buffer each call.
  19853. * Returns the Mesh.
  19854. */
  19855. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19856. return this;
  19857. };
  19858. /** Returns false by default, used by the class Mesh.
  19859. * Returns a boolean
  19860. */
  19861. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19862. return false;
  19863. };
  19864. /**
  19865. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  19866. * Returns a BoundingInfo
  19867. */
  19868. AbstractMesh.prototype.getBoundingInfo = function () {
  19869. if (this._masterMesh) {
  19870. return this._masterMesh.getBoundingInfo();
  19871. }
  19872. if (!this._boundingInfo) {
  19873. // this._boundingInfo is being created here
  19874. this._updateBoundingInfo();
  19875. }
  19876. // cannot be null.
  19877. return this._boundingInfo;
  19878. };
  19879. /**
  19880. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  19881. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  19882. */
  19883. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19884. if (includeDescendants === void 0) { includeDescendants = true; }
  19885. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19886. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19887. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19888. if (maxDimension === 0) {
  19889. return this;
  19890. }
  19891. var scale = 1 / maxDimension;
  19892. this.scaling.scaleInPlace(scale);
  19893. return this;
  19894. };
  19895. /**
  19896. * Sets a mesh new object BoundingInfo.
  19897. * Returns the AbstractMesh.
  19898. */
  19899. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19900. this._boundingInfo = boundingInfo;
  19901. return this;
  19902. };
  19903. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19904. get: function () {
  19905. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19906. },
  19907. enumerable: true,
  19908. configurable: true
  19909. });
  19910. AbstractMesh.prototype._preActivate = function () {
  19911. };
  19912. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19913. };
  19914. AbstractMesh.prototype._activate = function (renderId) {
  19915. this._renderId = renderId;
  19916. };
  19917. /**
  19918. * Returns the latest update of the World matrix
  19919. * Returns a Matrix.
  19920. */
  19921. AbstractMesh.prototype.getWorldMatrix = function () {
  19922. if (this._masterMesh) {
  19923. return this._masterMesh.getWorldMatrix();
  19924. }
  19925. return _super.prototype.getWorldMatrix.call(this);
  19926. };
  19927. /**
  19928. * Returns the latest update of the World matrix determinant.
  19929. */
  19930. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19931. if (this._masterMesh) {
  19932. return this._masterMesh._getWorldMatrixDeterminant();
  19933. }
  19934. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19935. };
  19936. // ================================== Point of View Movement =================================
  19937. /**
  19938. * Perform relative position change from the point of view of behind the front of the mesh.
  19939. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19940. * Supports definition of mesh facing forward or backward.
  19941. * @param {number} amountRight
  19942. * @param {number} amountUp
  19943. * @param {number} amountForward
  19944. *
  19945. * Returns the AbstractMesh.
  19946. */
  19947. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19948. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19949. return this;
  19950. };
  19951. /**
  19952. * Calculate relative position change from the point of view of behind the front of the mesh.
  19953. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19954. * Supports definition of mesh facing forward or backward.
  19955. * @param {number} amountRight
  19956. * @param {number} amountUp
  19957. * @param {number} amountForward
  19958. *
  19959. * Returns a new Vector3.
  19960. */
  19961. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19962. var rotMatrix = new BABYLON.Matrix();
  19963. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19964. rotQuaternion.toRotationMatrix(rotMatrix);
  19965. var translationDelta = BABYLON.Vector3.Zero();
  19966. var defForwardMult = this.definedFacingForward ? -1 : 1;
  19967. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  19968. return translationDelta;
  19969. };
  19970. // ================================== Point of View Rotation =================================
  19971. /**
  19972. * Perform relative rotation change from the point of view of behind the front of the mesh.
  19973. * Supports definition of mesh facing forward or backward.
  19974. * @param {number} flipBack
  19975. * @param {number} twirlClockwise
  19976. * @param {number} tiltRight
  19977. *
  19978. * Returns the AbstractMesh.
  19979. */
  19980. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19981. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  19982. return this;
  19983. };
  19984. /**
  19985. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  19986. * Supports definition of mesh facing forward or backward.
  19987. * @param {number} flipBack
  19988. * @param {number} twirlClockwise
  19989. * @param {number} tiltRight
  19990. *
  19991. * Returns a new Vector3.
  19992. */
  19993. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  19994. var defForwardMult = this.definedFacingForward ? 1 : -1;
  19995. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  19996. };
  19997. /**
  19998. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  19999. * @param includeDescendants Include bounding info from descendants as well (true by default).
  20000. */
  20001. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20002. if (includeDescendants === void 0) { includeDescendants = true; }
  20003. this.computeWorldMatrix(true);
  20004. var min;
  20005. var max;
  20006. var boundingInfo = this.getBoundingInfo();
  20007. if (!this.subMeshes) {
  20008. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20009. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20010. }
  20011. else {
  20012. min = boundingInfo.boundingBox.minimumWorld;
  20013. max = boundingInfo.boundingBox.maximumWorld;
  20014. }
  20015. if (includeDescendants) {
  20016. var descendants = this.getDescendants(false);
  20017. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20018. var descendant = descendants_1[_i];
  20019. var childMesh = descendant;
  20020. childMesh.computeWorldMatrix(true);
  20021. //make sure we have the needed params to get mix and max
  20022. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20023. continue;
  20024. }
  20025. var childBoundingInfo = childMesh.getBoundingInfo();
  20026. var boundingBox = childBoundingInfo.boundingBox;
  20027. var minBox = boundingBox.minimumWorld;
  20028. var maxBox = boundingBox.maximumWorld;
  20029. BABYLON.Tools.CheckExtends(minBox, min, max);
  20030. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20031. }
  20032. }
  20033. return {
  20034. min: min,
  20035. max: max
  20036. };
  20037. };
  20038. /**
  20039. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  20040. * Returns the AbstractMesh.
  20041. */
  20042. AbstractMesh.prototype._updateBoundingInfo = function () {
  20043. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20044. this._boundingInfo.update(this.worldMatrixFromCache);
  20045. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20046. return this;
  20047. };
  20048. /**
  20049. * Update a mesh's children BoundingInfo objects only.
  20050. * Returns the AbstractMesh.
  20051. */
  20052. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20053. if (!this.subMeshes) {
  20054. return this;
  20055. }
  20056. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20057. var subMesh = this.subMeshes[subIndex];
  20058. if (!subMesh.IsGlobal) {
  20059. subMesh.updateBoundingInfo(matrix);
  20060. }
  20061. }
  20062. return this;
  20063. };
  20064. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20065. // Bounding info
  20066. this._updateBoundingInfo();
  20067. };
  20068. /**
  20069. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20070. * A mesh is in the frustum if its bounding box intersects the frustum.
  20071. * Boolean returned.
  20072. */
  20073. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20074. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20075. };
  20076. /**
  20077. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20078. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20079. * Boolean returned.
  20080. */
  20081. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20082. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20083. ;
  20084. };
  20085. /**
  20086. * True if the mesh intersects another mesh or a SolidParticle object.
  20087. * 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)
  20088. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20089. * Returns a boolean.
  20090. */
  20091. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20092. if (precise === void 0) { precise = false; }
  20093. if (!this._boundingInfo || !mesh._boundingInfo) {
  20094. return false;
  20095. }
  20096. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20097. return true;
  20098. }
  20099. if (includeDescendants) {
  20100. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20101. var child = _a[_i];
  20102. if (child.intersectsMesh(mesh, precise, true)) {
  20103. return true;
  20104. }
  20105. }
  20106. }
  20107. return false;
  20108. };
  20109. /**
  20110. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  20111. * Returns a boolean.
  20112. */
  20113. AbstractMesh.prototype.intersectsPoint = function (point) {
  20114. if (!this._boundingInfo) {
  20115. return false;
  20116. }
  20117. return this._boundingInfo.intersectsPoint(point);
  20118. };
  20119. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20120. return this.physicsImpostor;
  20121. };
  20122. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20123. if (camera === void 0) { camera = null; }
  20124. if (!camera) {
  20125. camera = this.getScene().activeCamera;
  20126. }
  20127. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20128. };
  20129. /**
  20130. * Returns the distance from the mesh to the active camera.
  20131. * Returns a float.
  20132. */
  20133. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20134. if (camera === void 0) { camera = null; }
  20135. if (!camera) {
  20136. camera = this.getScene().activeCamera;
  20137. }
  20138. return this.absolutePosition.subtract(camera.position).length();
  20139. };
  20140. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20141. if (!this.physicsImpostor) {
  20142. return this;
  20143. }
  20144. this.physicsImpostor.applyImpulse(force, contactPoint);
  20145. return this;
  20146. };
  20147. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20148. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20149. return this;
  20150. }
  20151. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20152. mainPivot: pivot1,
  20153. connectedPivot: pivot2,
  20154. nativeParams: options
  20155. });
  20156. return this;
  20157. };
  20158. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20159. // Collisions
  20160. /**
  20161. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  20162. * Default `false`.
  20163. */
  20164. get: function () {
  20165. return this._checkCollisions;
  20166. },
  20167. set: function (collisionEnabled) {
  20168. this._checkCollisions = collisionEnabled;
  20169. if (this.getScene().workerCollisions) {
  20170. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20171. }
  20172. },
  20173. enumerable: true,
  20174. configurable: true
  20175. });
  20176. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20177. /**
  20178. * Gets Collider object used to compute collisions (not physics)
  20179. */
  20180. get: function () {
  20181. return this._collider;
  20182. },
  20183. enumerable: true,
  20184. configurable: true
  20185. });
  20186. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20187. var globalPosition = this.getAbsolutePosition();
  20188. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20189. if (!this._collider) {
  20190. this._collider = new BABYLON.Collider();
  20191. }
  20192. this._collider._radius = this.ellipsoid;
  20193. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20194. return this;
  20195. };
  20196. // Submeshes octree
  20197. /**
  20198. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20199. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  20200. * Returns an Octree of submeshes.
  20201. */
  20202. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20203. if (maxCapacity === void 0) { maxCapacity = 64; }
  20204. if (maxDepth === void 0) { maxDepth = 2; }
  20205. if (!this._submeshesOctree) {
  20206. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20207. }
  20208. this.computeWorldMatrix(true);
  20209. var boundingInfo = this.getBoundingInfo();
  20210. // Update octree
  20211. var bbox = boundingInfo.boundingBox;
  20212. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20213. return this._submeshesOctree;
  20214. };
  20215. // Collisions
  20216. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20217. this._generatePointsArray();
  20218. if (!this._positions) {
  20219. return this;
  20220. }
  20221. // Transformation
  20222. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20223. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20224. subMesh._lastColliderWorldVertices = [];
  20225. subMesh._trianglePlanes = [];
  20226. var start = subMesh.verticesStart;
  20227. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20228. for (var i = start; i < end; i++) {
  20229. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20230. }
  20231. }
  20232. // Collide
  20233. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20234. if (collider.collisionFound) {
  20235. collider.collidedMesh = this;
  20236. }
  20237. return this;
  20238. };
  20239. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20240. var subMeshes;
  20241. var len;
  20242. // Octrees
  20243. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20244. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20245. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20246. len = intersections.length;
  20247. subMeshes = intersections.data;
  20248. }
  20249. else {
  20250. subMeshes = this.subMeshes;
  20251. len = subMeshes.length;
  20252. }
  20253. for (var index = 0; index < len; index++) {
  20254. var subMesh = subMeshes[index];
  20255. // Bounding test
  20256. if (len > 1 && !subMesh._checkCollision(collider))
  20257. continue;
  20258. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20259. }
  20260. return this;
  20261. };
  20262. AbstractMesh.prototype._checkCollision = function (collider) {
  20263. // Bounding box test
  20264. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20265. return this;
  20266. // Transformation matrix
  20267. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20268. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20269. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20270. return this;
  20271. };
  20272. // Picking
  20273. AbstractMesh.prototype._generatePointsArray = function () {
  20274. return false;
  20275. };
  20276. /**
  20277. * Checks if the passed Ray intersects with the mesh.
  20278. * Returns an object PickingInfo.
  20279. */
  20280. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20281. var pickingInfo = new BABYLON.PickingInfo();
  20282. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20283. return pickingInfo;
  20284. }
  20285. if (!this._generatePointsArray()) {
  20286. return pickingInfo;
  20287. }
  20288. var intersectInfo = null;
  20289. // Octrees
  20290. var subMeshes;
  20291. var len;
  20292. if (this._submeshesOctree && this.useOctreeForPicking) {
  20293. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20294. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20295. len = intersections.length;
  20296. subMeshes = intersections.data;
  20297. }
  20298. else {
  20299. subMeshes = this.subMeshes;
  20300. len = subMeshes.length;
  20301. }
  20302. for (var index = 0; index < len; index++) {
  20303. var subMesh = subMeshes[index];
  20304. // Bounding test
  20305. if (len > 1 && !subMesh.canIntersects(ray))
  20306. continue;
  20307. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20308. if (currentIntersectInfo) {
  20309. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20310. intersectInfo = currentIntersectInfo;
  20311. intersectInfo.subMeshId = index;
  20312. if (fastCheck) {
  20313. break;
  20314. }
  20315. }
  20316. }
  20317. }
  20318. if (intersectInfo) {
  20319. // Get picked point
  20320. var world = this.getWorldMatrix();
  20321. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20322. var direction = ray.direction.clone();
  20323. direction = direction.scale(intersectInfo.distance);
  20324. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20325. var pickedPoint = worldOrigin.add(worldDirection);
  20326. // Return result
  20327. pickingInfo.hit = true;
  20328. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20329. pickingInfo.pickedPoint = pickedPoint;
  20330. pickingInfo.pickedMesh = this;
  20331. pickingInfo.bu = intersectInfo.bu || 0;
  20332. pickingInfo.bv = intersectInfo.bv || 0;
  20333. pickingInfo.faceId = intersectInfo.faceId;
  20334. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20335. return pickingInfo;
  20336. }
  20337. return pickingInfo;
  20338. };
  20339. /**
  20340. * Clones the mesh, used by the class Mesh.
  20341. * Just returns `null` for an AbstractMesh.
  20342. */
  20343. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20344. return null;
  20345. };
  20346. /**
  20347. * Disposes all the mesh submeshes.
  20348. * Returns the AbstractMesh.
  20349. */
  20350. AbstractMesh.prototype.releaseSubMeshes = function () {
  20351. if (this.subMeshes) {
  20352. while (this.subMeshes.length) {
  20353. this.subMeshes[0].dispose();
  20354. }
  20355. }
  20356. else {
  20357. this.subMeshes = new Array();
  20358. }
  20359. return this;
  20360. };
  20361. /**
  20362. * Releases resources associated with this abstract mesh.
  20363. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20364. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20365. */
  20366. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20367. var _this = this;
  20368. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20369. var index;
  20370. // Smart Array Retainers.
  20371. this.getScene().freeActiveMeshes();
  20372. this.getScene().freeRenderingGroups();
  20373. // Action manager
  20374. if (this.actionManager !== undefined && this.actionManager !== null) {
  20375. this.actionManager.dispose();
  20376. this.actionManager = null;
  20377. }
  20378. // Skeleton
  20379. this._skeleton = null;
  20380. // Physics
  20381. if (this.physicsImpostor) {
  20382. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20383. }
  20384. // Intersections in progress
  20385. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20386. var other = this._intersectionsInProgress[index];
  20387. var pos = other._intersectionsInProgress.indexOf(this);
  20388. other._intersectionsInProgress.splice(pos, 1);
  20389. }
  20390. this._intersectionsInProgress = [];
  20391. // Lights
  20392. var lights = this.getScene().lights;
  20393. lights.forEach(function (light) {
  20394. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20395. if (meshIndex !== -1) {
  20396. light.includedOnlyMeshes.splice(meshIndex, 1);
  20397. }
  20398. meshIndex = light.excludedMeshes.indexOf(_this);
  20399. if (meshIndex !== -1) {
  20400. light.excludedMeshes.splice(meshIndex, 1);
  20401. }
  20402. // Shadow generators
  20403. var generator = light.getShadowGenerator();
  20404. if (generator) {
  20405. var shadowMap = generator.getShadowMap();
  20406. if (shadowMap && shadowMap.renderList) {
  20407. meshIndex = shadowMap.renderList.indexOf(_this);
  20408. if (meshIndex !== -1) {
  20409. shadowMap.renderList.splice(meshIndex, 1);
  20410. }
  20411. }
  20412. }
  20413. });
  20414. // Edges
  20415. if (this._edgesRenderer) {
  20416. this._edgesRenderer.dispose();
  20417. this._edgesRenderer = null;
  20418. }
  20419. // SubMeshes
  20420. if (this.getClassName() !== "InstancedMesh") {
  20421. this.releaseSubMeshes();
  20422. }
  20423. // Octree
  20424. var sceneOctree = this.getScene().selectionOctree;
  20425. if (sceneOctree !== undefined && sceneOctree !== null) {
  20426. var index = sceneOctree.dynamicContent.indexOf(this);
  20427. if (index !== -1) {
  20428. sceneOctree.dynamicContent.splice(index, 1);
  20429. }
  20430. }
  20431. // Query
  20432. var engine = this.getScene().getEngine();
  20433. if (this._occlusionQuery) {
  20434. this._isOcclusionQueryInProgress = false;
  20435. engine.deleteQuery(this._occlusionQuery);
  20436. this._occlusionQuery = null;
  20437. }
  20438. // Engine
  20439. engine.wipeCaches();
  20440. // Remove from scene
  20441. this.getScene().removeMesh(this);
  20442. if (disposeMaterialAndTextures) {
  20443. if (this.material) {
  20444. this.material.dispose(false, true);
  20445. }
  20446. }
  20447. if (!doNotRecurse) {
  20448. // Particles
  20449. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20450. if (this.getScene().particleSystems[index].emitter === this) {
  20451. this.getScene().particleSystems[index].dispose();
  20452. index--;
  20453. }
  20454. }
  20455. }
  20456. // facet data
  20457. if (this._facetDataEnabled) {
  20458. this.disableFacetData();
  20459. }
  20460. this.onAfterWorldMatrixUpdateObservable.clear();
  20461. this.onCollideObservable.clear();
  20462. this.onCollisionPositionChangeObservable.clear();
  20463. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20464. };
  20465. /**
  20466. * Adds the passed mesh as a child to the current mesh.
  20467. * Returns the AbstractMesh.
  20468. */
  20469. AbstractMesh.prototype.addChild = function (mesh) {
  20470. mesh.setParent(this);
  20471. return this;
  20472. };
  20473. /**
  20474. * Removes the passed mesh from the current mesh children list.
  20475. * Returns the AbstractMesh.
  20476. */
  20477. AbstractMesh.prototype.removeChild = function (mesh) {
  20478. mesh.setParent(null);
  20479. return this;
  20480. };
  20481. // Facet data
  20482. /**
  20483. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  20484. * Returns the AbstractMesh.
  20485. */
  20486. AbstractMesh.prototype._initFacetData = function () {
  20487. if (!this._facetNormals) {
  20488. this._facetNormals = new Array();
  20489. }
  20490. if (!this._facetPositions) {
  20491. this._facetPositions = new Array();
  20492. }
  20493. if (!this._facetPartitioning) {
  20494. this._facetPartitioning = new Array();
  20495. }
  20496. this._facetNb = (this.getIndices().length / 3) | 0;
  20497. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20498. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20499. for (var f = 0; f < this._facetNb; f++) {
  20500. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20501. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20502. }
  20503. this._facetDataEnabled = true;
  20504. return this;
  20505. };
  20506. /**
  20507. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20508. * This method can be called within the render loop.
  20509. * 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.
  20510. * Returns the AbstractMesh.
  20511. */
  20512. AbstractMesh.prototype.updateFacetData = function () {
  20513. if (!this._facetDataEnabled) {
  20514. this._initFacetData();
  20515. }
  20516. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20517. var indices = this.getIndices();
  20518. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20519. var bInfo = this.getBoundingInfo();
  20520. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20521. // init arrays, matrix and sort function on first call
  20522. this._facetDepthSortEnabled = true;
  20523. if (indices instanceof Uint16Array) {
  20524. this._depthSortedIndices = new Uint16Array(indices);
  20525. }
  20526. else if (indices instanceof Uint32Array) {
  20527. this._depthSortedIndices = new Uint32Array(indices);
  20528. }
  20529. else {
  20530. var needs32bits = false;
  20531. for (var i = 0; i < indices.length; i++) {
  20532. if (indices[i] > 65535) {
  20533. needs32bits = true;
  20534. break;
  20535. }
  20536. }
  20537. if (needs32bits) {
  20538. this._depthSortedIndices = new Uint32Array(indices);
  20539. }
  20540. else {
  20541. this._depthSortedIndices = new Uint16Array(indices);
  20542. }
  20543. }
  20544. this._facetDepthSortFunction = function (f1, f2) {
  20545. return (f2.sqDistance - f1.sqDistance);
  20546. };
  20547. if (!this._facetDepthSortFrom) {
  20548. var camera = this.getScene().activeCamera;
  20549. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20550. }
  20551. this._depthSortedFacets = [];
  20552. for (var f = 0; f < this._facetNb; f++) {
  20553. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20554. this._depthSortedFacets.push(depthSortedFacet);
  20555. }
  20556. this._invertedMatrix = BABYLON.Matrix.Identity();
  20557. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20558. }
  20559. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20560. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20561. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20562. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20563. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20564. this._subDiv.max = this._partitioningSubdivisions;
  20565. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20566. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20567. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20568. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20569. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20570. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20571. // set the parameters for ComputeNormals()
  20572. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20573. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20574. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20575. this._facetParameters.bInfo = bInfo;
  20576. this._facetParameters.bbSize = this._bbSize;
  20577. this._facetParameters.subDiv = this._subDiv;
  20578. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20579. this._facetParameters.depthSort = this._facetDepthSort;
  20580. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20581. this.computeWorldMatrix(true);
  20582. this._worldMatrix.invertToRef(this._invertedMatrix);
  20583. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20584. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20585. }
  20586. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20587. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20588. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20589. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20590. var l = (this._depthSortedIndices.length / 3) | 0;
  20591. for (var f = 0; f < l; f++) {
  20592. var sind = this._depthSortedFacets[f].ind;
  20593. this._depthSortedIndices[f * 3] = indices[sind];
  20594. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20595. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20596. }
  20597. this.updateIndices(this._depthSortedIndices);
  20598. }
  20599. return this;
  20600. };
  20601. /**
  20602. * Returns the facetLocalNormals array.
  20603. * The normals are expressed in the mesh local space.
  20604. */
  20605. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20606. if (!this._facetNormals) {
  20607. this.updateFacetData();
  20608. }
  20609. return this._facetNormals;
  20610. };
  20611. /**
  20612. * Returns the facetLocalPositions array.
  20613. * The facet positions are expressed in the mesh local space.
  20614. */
  20615. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20616. if (!this._facetPositions) {
  20617. this.updateFacetData();
  20618. }
  20619. return this._facetPositions;
  20620. };
  20621. /**
  20622. * Returns the facetLocalPartioning array.
  20623. */
  20624. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20625. if (!this._facetPartitioning) {
  20626. this.updateFacetData();
  20627. }
  20628. return this._facetPartitioning;
  20629. };
  20630. /**
  20631. * Returns the i-th facet position in the world system.
  20632. * This method allocates a new Vector3 per call.
  20633. */
  20634. AbstractMesh.prototype.getFacetPosition = function (i) {
  20635. var pos = BABYLON.Vector3.Zero();
  20636. this.getFacetPositionToRef(i, pos);
  20637. return pos;
  20638. };
  20639. /**
  20640. * Sets the reference Vector3 with the i-th facet position in the world system.
  20641. * Returns the AbstractMesh.
  20642. */
  20643. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20644. var localPos = (this.getFacetLocalPositions())[i];
  20645. var world = this.getWorldMatrix();
  20646. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20647. return this;
  20648. };
  20649. /**
  20650. * Returns the i-th facet normal in the world system.
  20651. * This method allocates a new Vector3 per call.
  20652. */
  20653. AbstractMesh.prototype.getFacetNormal = function (i) {
  20654. var norm = BABYLON.Vector3.Zero();
  20655. this.getFacetNormalToRef(i, norm);
  20656. return norm;
  20657. };
  20658. /**
  20659. * Sets the reference Vector3 with the i-th facet normal in the world system.
  20660. * Returns the AbstractMesh.
  20661. */
  20662. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20663. var localNorm = (this.getFacetLocalNormals())[i];
  20664. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20665. return this;
  20666. };
  20667. /**
  20668. * 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).
  20669. */
  20670. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20671. var bInfo = this.getBoundingInfo();
  20672. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20673. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20674. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20675. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20676. return null;
  20677. }
  20678. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20679. };
  20680. /**
  20681. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  20682. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  20683. * 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.
  20684. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20685. * 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.
  20686. */
  20687. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20688. if (checkFace === void 0) { checkFace = false; }
  20689. if (facing === void 0) { facing = true; }
  20690. var world = this.getWorldMatrix();
  20691. var invMat = BABYLON.Tmp.Matrix[5];
  20692. world.invertToRef(invMat);
  20693. var invVect = BABYLON.Tmp.Vector3[8];
  20694. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20695. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20696. if (projected) {
  20697. // tranform the local computed projected vector to world coordinates
  20698. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20699. }
  20700. return closest;
  20701. };
  20702. /**
  20703. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  20704. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  20705. * 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.
  20706. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  20707. * 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.
  20708. */
  20709. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20710. if (checkFace === void 0) { checkFace = false; }
  20711. if (facing === void 0) { facing = true; }
  20712. var closest = null;
  20713. var tmpx = 0.0;
  20714. var tmpy = 0.0;
  20715. var tmpz = 0.0;
  20716. var d = 0.0; // tmp dot facet normal * facet position
  20717. var t0 = 0.0;
  20718. var projx = 0.0;
  20719. var projy = 0.0;
  20720. var projz = 0.0;
  20721. // Get all the facets in the same partitioning block than (x, y, z)
  20722. var facetPositions = this.getFacetLocalPositions();
  20723. var facetNormals = this.getFacetLocalNormals();
  20724. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20725. if (!facetsInBlock) {
  20726. return null;
  20727. }
  20728. // Get the closest facet to (x, y, z)
  20729. var shortest = Number.MAX_VALUE; // init distance vars
  20730. var tmpDistance = shortest;
  20731. var fib; // current facet in the block
  20732. var norm; // current facet normal
  20733. var p0; // current facet barycenter position
  20734. // loop on all the facets in the current partitioning block
  20735. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20736. fib = facetsInBlock[idx];
  20737. norm = facetNormals[fib];
  20738. p0 = facetPositions[fib];
  20739. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20740. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20741. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20742. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20743. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20744. projx = x + norm.x * t0;
  20745. projy = y + norm.y * t0;
  20746. projz = z + norm.z * t0;
  20747. tmpx = projx - x;
  20748. tmpy = projy - y;
  20749. tmpz = projz - z;
  20750. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20751. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20752. shortest = tmpDistance;
  20753. closest = fib;
  20754. if (projected) {
  20755. projected.x = projx;
  20756. projected.y = projy;
  20757. projected.z = projz;
  20758. }
  20759. }
  20760. }
  20761. }
  20762. return closest;
  20763. };
  20764. /**
  20765. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20766. */
  20767. AbstractMesh.prototype.getFacetDataParameters = function () {
  20768. return this._facetParameters;
  20769. };
  20770. /**
  20771. * Disables the feature FacetData and frees the related memory.
  20772. * Returns the AbstractMesh.
  20773. */
  20774. AbstractMesh.prototype.disableFacetData = function () {
  20775. if (this._facetDataEnabled) {
  20776. this._facetDataEnabled = false;
  20777. this._facetPositions = new Array();
  20778. this._facetNormals = new Array();
  20779. this._facetPartitioning = new Array();
  20780. this._facetParameters = null;
  20781. this._depthSortedIndices = new Uint32Array(0);
  20782. }
  20783. return this;
  20784. };
  20785. /**
  20786. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  20787. * Returns the mesh.
  20788. */
  20789. AbstractMesh.prototype.updateIndices = function (indices) {
  20790. return this;
  20791. };
  20792. /**
  20793. * The mesh Geometry. Actually used by the Mesh object.
  20794. * Returns a blank geometry object.
  20795. */
  20796. /**
  20797. * Creates new normals data for the mesh.
  20798. * @param updatable.
  20799. */
  20800. AbstractMesh.prototype.createNormals = function (updatable) {
  20801. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20802. var indices = this.getIndices();
  20803. var normals;
  20804. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20805. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20806. }
  20807. else {
  20808. normals = [];
  20809. }
  20810. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20811. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20812. };
  20813. /**
  20814. * Align the mesh with a normal.
  20815. * Returns the mesh.
  20816. */
  20817. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20818. if (!upDirection) {
  20819. upDirection = BABYLON.Axis.Y;
  20820. }
  20821. var axisX = BABYLON.Tmp.Vector3[0];
  20822. var axisZ = BABYLON.Tmp.Vector3[1];
  20823. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20824. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20825. if (this.rotationQuaternion) {
  20826. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20827. }
  20828. else {
  20829. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20830. }
  20831. return this;
  20832. };
  20833. AbstractMesh.prototype.checkOcclusionQuery = function () {
  20834. var engine = this.getEngine();
  20835. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20836. this._isOccluded = false;
  20837. return;
  20838. }
  20839. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20840. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20841. if (isOcclusionQueryAvailable) {
  20842. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20843. this._isOcclusionQueryInProgress = false;
  20844. this._occlusionInternalRetryCounter = 0;
  20845. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20846. }
  20847. else {
  20848. this._occlusionInternalRetryCounter++;
  20849. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20850. this._isOcclusionQueryInProgress = false;
  20851. this._occlusionInternalRetryCounter = 0;
  20852. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20853. // if strict continue the last state of the object.
  20854. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20855. }
  20856. else {
  20857. return;
  20858. }
  20859. }
  20860. }
  20861. var scene = this.getScene();
  20862. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20863. if (!this._occlusionQuery) {
  20864. this._occlusionQuery = engine.createQuery();
  20865. }
  20866. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20867. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20868. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20869. this._isOcclusionQueryInProgress = true;
  20870. };
  20871. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20872. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20873. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20874. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20875. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20876. return AbstractMesh;
  20877. }(BABYLON.TransformNode));
  20878. BABYLON.AbstractMesh = AbstractMesh;
  20879. })(BABYLON || (BABYLON = {}));
  20880. //# sourceMappingURL=babylon.abstractMesh.js.map
  20881. var BABYLON;
  20882. (function (BABYLON) {
  20883. /**
  20884. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  20885. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  20886. * 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.
  20887. */
  20888. var Light = /** @class */ (function (_super) {
  20889. __extends(Light, _super);
  20890. /**
  20891. * Creates a Light object in the scene.
  20892. * Documentation : http://doc.babylonjs.com/tutorials/lights
  20893. * @param name The firendly name of the light
  20894. * @param scene The scene the light belongs too
  20895. */
  20896. function Light(name, scene) {
  20897. var _this = _super.call(this, name, scene) || this;
  20898. /**
  20899. * Diffuse gives the basic color to an object.
  20900. */
  20901. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  20902. /**
  20903. * Specular produces a highlight color on an object.
  20904. * Note: This is note affecting PBR materials.
  20905. */
  20906. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  20907. /**
  20908. * Strength of the light.
  20909. * Note: By default it is define in the framework own unit.
  20910. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  20911. */
  20912. _this.intensity = 1.0;
  20913. /**
  20914. * Defines how far from the source the light is impacting in scene units.
  20915. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  20916. */
  20917. _this.range = Number.MAX_VALUE;
  20918. /**
  20919. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  20920. * of light.
  20921. */
  20922. _this._photometricScale = 1.0;
  20923. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  20924. _this._radius = 0.00001;
  20925. /**
  20926. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  20927. * exceeding the number allowed of the materials.
  20928. */
  20929. _this.renderPriority = 0;
  20930. /**
  20931. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  20932. * the current shadow generator.
  20933. */
  20934. _this.shadowEnabled = true;
  20935. _this._excludeWithLayerMask = 0;
  20936. _this._includeOnlyWithLayerMask = 0;
  20937. _this._lightmapMode = 0;
  20938. /**
  20939. * @ignore Internal use only.
  20940. */
  20941. _this._excludedMeshesIds = new Array();
  20942. /**
  20943. * @ignore Internal use only.
  20944. */
  20945. _this._includedOnlyMeshesIds = new Array();
  20946. _this.getScene().addLight(_this);
  20947. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  20948. _this._buildUniformLayout();
  20949. _this.includedOnlyMeshes = new Array();
  20950. _this.excludedMeshes = new Array();
  20951. _this._resyncMeshes();
  20952. return _this;
  20953. }
  20954. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  20955. /**
  20956. * If every light affecting the material is in this lightmapMode,
  20957. * material.lightmapTexture adds or multiplies
  20958. * (depends on material.useLightmapAsShadowmap)
  20959. * after every other light calculations.
  20960. */
  20961. get: function () {
  20962. return Light._LIGHTMAP_DEFAULT;
  20963. },
  20964. enumerable: true,
  20965. configurable: true
  20966. });
  20967. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  20968. /**
  20969. * material.lightmapTexture as only diffuse lighting from this light
  20970. * adds only specular lighting from this light
  20971. * adds dynamic shadows
  20972. */
  20973. get: function () {
  20974. return Light._LIGHTMAP_SPECULAR;
  20975. },
  20976. enumerable: true,
  20977. configurable: true
  20978. });
  20979. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  20980. /**
  20981. * material.lightmapTexture as only lighting
  20982. * no light calculation from this light
  20983. * only adds dynamic shadows from this light
  20984. */
  20985. get: function () {
  20986. return Light._LIGHTMAP_SHADOWSONLY;
  20987. },
  20988. enumerable: true,
  20989. configurable: true
  20990. });
  20991. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  20992. /**
  20993. * Each light type uses the default quantity according to its type:
  20994. * point/spot lights use luminous intensity
  20995. * directional lights use illuminance
  20996. */
  20997. get: function () {
  20998. return Light._INTENSITYMODE_AUTOMATIC;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21004. /**
  21005. * lumen (lm)
  21006. */
  21007. get: function () {
  21008. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21009. },
  21010. enumerable: true,
  21011. configurable: true
  21012. });
  21013. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21014. /**
  21015. * candela (lm/sr)
  21016. */
  21017. get: function () {
  21018. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21019. },
  21020. enumerable: true,
  21021. configurable: true
  21022. });
  21023. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21024. /**
  21025. * lux (lm/m^2)
  21026. */
  21027. get: function () {
  21028. return Light._INTENSITYMODE_ILLUMINANCE;
  21029. },
  21030. enumerable: true,
  21031. configurable: true
  21032. });
  21033. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21034. /**
  21035. * nit (cd/m^2)
  21036. */
  21037. get: function () {
  21038. return Light._INTENSITYMODE_LUMINANCE;
  21039. },
  21040. enumerable: true,
  21041. configurable: true
  21042. });
  21043. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21044. /**
  21045. * Light type const id of the point light.
  21046. */
  21047. get: function () {
  21048. return Light._LIGHTTYPEID_POINTLIGHT;
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21054. /**
  21055. * Light type const id of the directional light.
  21056. */
  21057. get: function () {
  21058. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21059. },
  21060. enumerable: true,
  21061. configurable: true
  21062. });
  21063. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21064. /**
  21065. * Light type const id of the spot light.
  21066. */
  21067. get: function () {
  21068. return Light._LIGHTTYPEID_SPOTLIGHT;
  21069. },
  21070. enumerable: true,
  21071. configurable: true
  21072. });
  21073. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21074. /**
  21075. * Light type const id of the hemispheric light.
  21076. */
  21077. get: function () {
  21078. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21079. },
  21080. enumerable: true,
  21081. configurable: true
  21082. });
  21083. Object.defineProperty(Light.prototype, "intensityMode", {
  21084. /**
  21085. * Gets the photometric scale used to interpret the intensity.
  21086. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21087. */
  21088. get: function () {
  21089. return this._intensityMode;
  21090. },
  21091. /**
  21092. * Sets the photometric scale used to interpret the intensity.
  21093. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21094. */
  21095. set: function (value) {
  21096. this._intensityMode = value;
  21097. this._computePhotometricScale();
  21098. },
  21099. enumerable: true,
  21100. configurable: true
  21101. });
  21102. ;
  21103. ;
  21104. Object.defineProperty(Light.prototype, "radius", {
  21105. /**
  21106. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21107. */
  21108. get: function () {
  21109. return this._radius;
  21110. },
  21111. /**
  21112. * sets the light radius used by PBR Materials to simulate soft area lights.
  21113. */
  21114. set: function (value) {
  21115. this._radius = value;
  21116. this._computePhotometricScale();
  21117. },
  21118. enumerable: true,
  21119. configurable: true
  21120. });
  21121. ;
  21122. ;
  21123. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21124. /**
  21125. * Gets the only meshes impacted by this light.
  21126. */
  21127. get: function () {
  21128. return this._includedOnlyMeshes;
  21129. },
  21130. /**
  21131. * Sets the only meshes impacted by this light.
  21132. */
  21133. set: function (value) {
  21134. this._includedOnlyMeshes = value;
  21135. this._hookArrayForIncludedOnly(value);
  21136. },
  21137. enumerable: true,
  21138. configurable: true
  21139. });
  21140. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21141. /**
  21142. * Gets the meshes not impacted by this light.
  21143. */
  21144. get: function () {
  21145. return this._excludedMeshes;
  21146. },
  21147. /**
  21148. * Sets the meshes not impacted by this light.
  21149. */
  21150. set: function (value) {
  21151. this._excludedMeshes = value;
  21152. this._hookArrayForExcluded(value);
  21153. },
  21154. enumerable: true,
  21155. configurable: true
  21156. });
  21157. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21158. /**
  21159. * Gets the layer id use to find what meshes are not impacted by the light.
  21160. * Inactive if 0
  21161. */
  21162. get: function () {
  21163. return this._excludeWithLayerMask;
  21164. },
  21165. /**
  21166. * Sets the layer id use to find what meshes are not impacted by the light.
  21167. * Inactive if 0
  21168. */
  21169. set: function (value) {
  21170. this._excludeWithLayerMask = value;
  21171. this._resyncMeshes();
  21172. },
  21173. enumerable: true,
  21174. configurable: true
  21175. });
  21176. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21177. /**
  21178. * Gets the layer id use to find what meshes are impacted by the light.
  21179. * Inactive if 0
  21180. */
  21181. get: function () {
  21182. return this._includeOnlyWithLayerMask;
  21183. },
  21184. /**
  21185. * Sets the layer id use to find what meshes are impacted by the light.
  21186. * Inactive if 0
  21187. */
  21188. set: function (value) {
  21189. this._includeOnlyWithLayerMask = value;
  21190. this._resyncMeshes();
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(Light.prototype, "lightmapMode", {
  21196. /**
  21197. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21198. */
  21199. get: function () {
  21200. return this._lightmapMode;
  21201. },
  21202. /**
  21203. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21204. */
  21205. set: function (value) {
  21206. if (this._lightmapMode === value) {
  21207. return;
  21208. }
  21209. this._lightmapMode = value;
  21210. this._markMeshesAsLightDirty();
  21211. },
  21212. enumerable: true,
  21213. configurable: true
  21214. });
  21215. /**
  21216. * Returns the string "Light".
  21217. * @returns the class name
  21218. */
  21219. Light.prototype.getClassName = function () {
  21220. return "Light";
  21221. };
  21222. /**
  21223. * Converts the light information to a readable string for debug purpose.
  21224. * @param fullDetails Supports for multiple levels of logging within scene loading
  21225. * @returns the human readable light info
  21226. */
  21227. Light.prototype.toString = function (fullDetails) {
  21228. var ret = "Name: " + this.name;
  21229. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21230. if (this.animations) {
  21231. for (var i = 0; i < this.animations.length; i++) {
  21232. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21233. }
  21234. }
  21235. if (fullDetails) {
  21236. }
  21237. return ret;
  21238. };
  21239. /**
  21240. * Set the enabled state of this node.
  21241. * @param value - the new enabled state
  21242. */
  21243. Light.prototype.setEnabled = function (value) {
  21244. _super.prototype.setEnabled.call(this, value);
  21245. this._resyncMeshes();
  21246. };
  21247. /**
  21248. * Returns the Light associated shadow generator if any.
  21249. * @return the associated shadow generator.
  21250. */
  21251. Light.prototype.getShadowGenerator = function () {
  21252. return this._shadowGenerator;
  21253. };
  21254. /**
  21255. * Returns a Vector3, the absolute light position in the World.
  21256. * @returns the world space position of the light
  21257. */
  21258. Light.prototype.getAbsolutePosition = function () {
  21259. return BABYLON.Vector3.Zero();
  21260. };
  21261. /**
  21262. * Specifies if the light will affect the passed mesh.
  21263. * @param mesh The mesh to test against the light
  21264. * @return true the mesh is affected otherwise, false.
  21265. */
  21266. Light.prototype.canAffectMesh = function (mesh) {
  21267. if (!mesh) {
  21268. return true;
  21269. }
  21270. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21271. return false;
  21272. }
  21273. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21274. return false;
  21275. }
  21276. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21277. return false;
  21278. }
  21279. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21280. return false;
  21281. }
  21282. return true;
  21283. };
  21284. /**
  21285. * Computes and Returns the light World matrix.
  21286. * @returns the world matrix
  21287. */
  21288. Light.prototype.getWorldMatrix = function () {
  21289. this._currentRenderId = this.getScene().getRenderId();
  21290. this._childRenderId = this._currentRenderId;
  21291. var worldMatrix = this._getWorldMatrix();
  21292. if (this.parent && this.parent.getWorldMatrix) {
  21293. if (!this._parentedWorldMatrix) {
  21294. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21295. }
  21296. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21297. this._markSyncedWithParent();
  21298. return this._parentedWorldMatrix;
  21299. }
  21300. return worldMatrix;
  21301. };
  21302. /**
  21303. * Sort function to order lights for rendering.
  21304. * @param a First Light object to compare to second.
  21305. * @param b Second Light object to compare first.
  21306. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21307. */
  21308. Light.CompareLightsPriority = function (a, b) {
  21309. //shadow-casting lights have priority over non-shadow-casting lights
  21310. //the renderPrioirty is a secondary sort criterion
  21311. if (a.shadowEnabled !== b.shadowEnabled) {
  21312. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21313. }
  21314. return b.renderPriority - a.renderPriority;
  21315. };
  21316. /**
  21317. * Releases resources associated with this node.
  21318. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21319. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21320. */
  21321. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21322. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21323. if (this._shadowGenerator) {
  21324. this._shadowGenerator.dispose();
  21325. this._shadowGenerator = null;
  21326. }
  21327. // Animations
  21328. this.getScene().stopAnimation(this);
  21329. // Remove from meshes
  21330. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21331. var mesh = _a[_i];
  21332. mesh._removeLightSource(this);
  21333. }
  21334. this._uniformBuffer.dispose();
  21335. // Remove from scene
  21336. this.getScene().removeLight(this);
  21337. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21338. };
  21339. /**
  21340. * Returns the light type ID (integer).
  21341. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21342. */
  21343. Light.prototype.getTypeID = function () {
  21344. return 0;
  21345. };
  21346. /**
  21347. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21348. * @returns the scaled intensity in intensity mode unit
  21349. */
  21350. Light.prototype.getScaledIntensity = function () {
  21351. return this._photometricScale * this.intensity;
  21352. };
  21353. /**
  21354. * Returns a new Light object, named "name", from the current one.
  21355. * @param name The name of the cloned light
  21356. * @returns the new created light
  21357. */
  21358. Light.prototype.clone = function (name) {
  21359. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21360. if (!constructor) {
  21361. return null;
  21362. }
  21363. return BABYLON.SerializationHelper.Clone(constructor, this);
  21364. };
  21365. /**
  21366. * Serializes the current light into a Serialization object.
  21367. * @returns the serialized object.
  21368. */
  21369. Light.prototype.serialize = function () {
  21370. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21371. // Type
  21372. serializationObject.type = this.getTypeID();
  21373. // Parent
  21374. if (this.parent) {
  21375. serializationObject.parentId = this.parent.id;
  21376. }
  21377. // Inclusion / exclusions
  21378. if (this.excludedMeshes.length > 0) {
  21379. serializationObject.excludedMeshesIds = [];
  21380. this.excludedMeshes.forEach(function (mesh) {
  21381. serializationObject.excludedMeshesIds.push(mesh.id);
  21382. });
  21383. }
  21384. if (this.includedOnlyMeshes.length > 0) {
  21385. serializationObject.includedOnlyMeshesIds = [];
  21386. this.includedOnlyMeshes.forEach(function (mesh) {
  21387. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21388. });
  21389. }
  21390. // Animations
  21391. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21392. serializationObject.ranges = this.serializeAnimationRanges();
  21393. return serializationObject;
  21394. };
  21395. /**
  21396. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21397. * This new light is named "name" and added to the passed scene.
  21398. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21399. * @param name The friendly name of the light
  21400. * @param scene The scene the new light will belong to
  21401. * @returns the constructor function
  21402. */
  21403. Light.GetConstructorFromName = function (type, name, scene) {
  21404. switch (type) {
  21405. case 0:
  21406. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21407. case 1:
  21408. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21409. case 2:
  21410. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21411. case 3:
  21412. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21413. }
  21414. return null;
  21415. };
  21416. /**
  21417. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21418. * @param parsedLight The JSON representation of the light
  21419. * @param scene The scene to create the parsed light in
  21420. * @returns the created light after parsing
  21421. */
  21422. Light.Parse = function (parsedLight, scene) {
  21423. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21424. if (!constructor) {
  21425. return null;
  21426. }
  21427. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21428. // Inclusion / exclusions
  21429. if (parsedLight.excludedMeshesIds) {
  21430. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21431. }
  21432. if (parsedLight.includedOnlyMeshesIds) {
  21433. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21434. }
  21435. // Parent
  21436. if (parsedLight.parentId) {
  21437. light._waitingParentId = parsedLight.parentId;
  21438. }
  21439. // Animations
  21440. if (parsedLight.animations) {
  21441. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21442. var parsedAnimation = parsedLight.animations[animationIndex];
  21443. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21444. }
  21445. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21446. }
  21447. if (parsedLight.autoAnimate) {
  21448. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21449. }
  21450. return light;
  21451. };
  21452. Light.prototype._hookArrayForExcluded = function (array) {
  21453. var _this = this;
  21454. var oldPush = array.push;
  21455. array.push = function () {
  21456. var items = [];
  21457. for (var _i = 0; _i < arguments.length; _i++) {
  21458. items[_i] = arguments[_i];
  21459. }
  21460. var result = oldPush.apply(array, items);
  21461. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21462. var item = items_1[_a];
  21463. item._resyncLighSource(_this);
  21464. }
  21465. return result;
  21466. };
  21467. var oldSplice = array.splice;
  21468. array.splice = function (index, deleteCount) {
  21469. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21470. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21471. var item = deleted_1[_i];
  21472. item._resyncLighSource(_this);
  21473. }
  21474. return deleted;
  21475. };
  21476. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21477. var item = array_1[_i];
  21478. item._resyncLighSource(this);
  21479. }
  21480. };
  21481. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21482. var _this = this;
  21483. var oldPush = array.push;
  21484. array.push = function () {
  21485. var items = [];
  21486. for (var _i = 0; _i < arguments.length; _i++) {
  21487. items[_i] = arguments[_i];
  21488. }
  21489. var result = oldPush.apply(array, items);
  21490. _this._resyncMeshes();
  21491. return result;
  21492. };
  21493. var oldSplice = array.splice;
  21494. array.splice = function (index, deleteCount) {
  21495. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21496. _this._resyncMeshes();
  21497. return deleted;
  21498. };
  21499. this._resyncMeshes();
  21500. };
  21501. Light.prototype._resyncMeshes = function () {
  21502. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21503. var mesh = _a[_i];
  21504. mesh._resyncLighSource(this);
  21505. }
  21506. };
  21507. /**
  21508. * Forces the meshes to update their light related information in their rendering used effects
  21509. * @ignore Internal Use Only
  21510. */
  21511. Light.prototype._markMeshesAsLightDirty = function () {
  21512. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21513. var mesh = _a[_i];
  21514. if (mesh._lightSources.indexOf(this) !== -1) {
  21515. mesh._markSubMeshesAsLightDirty();
  21516. }
  21517. }
  21518. };
  21519. /**
  21520. * Recomputes the cached photometric scale if needed.
  21521. */
  21522. Light.prototype._computePhotometricScale = function () {
  21523. this._photometricScale = this._getPhotometricScale();
  21524. this.getScene().resetCachedMaterial();
  21525. };
  21526. /**
  21527. * Returns the Photometric Scale according to the light type and intensity mode.
  21528. */
  21529. Light.prototype._getPhotometricScale = function () {
  21530. var photometricScale = 0.0;
  21531. var lightTypeID = this.getTypeID();
  21532. //get photometric mode
  21533. var photometricMode = this.intensityMode;
  21534. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21535. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21536. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21537. }
  21538. else {
  21539. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21540. }
  21541. }
  21542. //compute photometric scale
  21543. switch (lightTypeID) {
  21544. case Light.LIGHTTYPEID_POINTLIGHT:
  21545. case Light.LIGHTTYPEID_SPOTLIGHT:
  21546. switch (photometricMode) {
  21547. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21548. photometricScale = 1.0 / (4.0 * Math.PI);
  21549. break;
  21550. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21551. photometricScale = 1.0;
  21552. break;
  21553. case Light.INTENSITYMODE_LUMINANCE:
  21554. photometricScale = this.radius * this.radius;
  21555. break;
  21556. }
  21557. break;
  21558. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21559. switch (photometricMode) {
  21560. case Light.INTENSITYMODE_ILLUMINANCE:
  21561. photometricScale = 1.0;
  21562. break;
  21563. case Light.INTENSITYMODE_LUMINANCE:
  21564. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21565. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21566. var apexAngleRadians = this.radius;
  21567. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21568. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21569. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21570. photometricScale = solidAngle;
  21571. break;
  21572. }
  21573. break;
  21574. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21575. // No fall off in hemisperic light.
  21576. photometricScale = 1.0;
  21577. break;
  21578. }
  21579. return photometricScale;
  21580. };
  21581. /**
  21582. * Reorder the light in the scene according to their defined priority.
  21583. * @ignore Internal Use Only
  21584. */
  21585. Light.prototype._reorderLightsInScene = function () {
  21586. var scene = this.getScene();
  21587. if (this._renderPriority != 0) {
  21588. scene.requireLightSorting = true;
  21589. }
  21590. this.getScene().sortLightsByPriority();
  21591. };
  21592. //lightmapMode Consts
  21593. Light._LIGHTMAP_DEFAULT = 0;
  21594. Light._LIGHTMAP_SPECULAR = 1;
  21595. Light._LIGHTMAP_SHADOWSONLY = 2;
  21596. // Intensity Mode Consts
  21597. Light._INTENSITYMODE_AUTOMATIC = 0;
  21598. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21599. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21600. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21601. Light._INTENSITYMODE_LUMINANCE = 4;
  21602. // Light types ids const.
  21603. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21604. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21605. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21606. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21607. __decorate([
  21608. BABYLON.serializeAsColor3()
  21609. ], Light.prototype, "diffuse", void 0);
  21610. __decorate([
  21611. BABYLON.serializeAsColor3()
  21612. ], Light.prototype, "specular", void 0);
  21613. __decorate([
  21614. BABYLON.serialize()
  21615. ], Light.prototype, "intensity", void 0);
  21616. __decorate([
  21617. BABYLON.serialize()
  21618. ], Light.prototype, "range", void 0);
  21619. __decorate([
  21620. BABYLON.serialize()
  21621. ], Light.prototype, "intensityMode", null);
  21622. __decorate([
  21623. BABYLON.serialize()
  21624. ], Light.prototype, "radius", null);
  21625. __decorate([
  21626. BABYLON.serialize()
  21627. ], Light.prototype, "_renderPriority", void 0);
  21628. __decorate([
  21629. BABYLON.expandToProperty("_reorderLightsInScene")
  21630. ], Light.prototype, "renderPriority", void 0);
  21631. __decorate([
  21632. BABYLON.serialize()
  21633. ], Light.prototype, "shadowEnabled", void 0);
  21634. __decorate([
  21635. BABYLON.serialize("excludeWithLayerMask")
  21636. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21637. __decorate([
  21638. BABYLON.serialize("includeOnlyWithLayerMask")
  21639. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21640. __decorate([
  21641. BABYLON.serialize("lightmapMode")
  21642. ], Light.prototype, "_lightmapMode", void 0);
  21643. return Light;
  21644. }(BABYLON.Node));
  21645. BABYLON.Light = Light;
  21646. })(BABYLON || (BABYLON = {}));
  21647. //# sourceMappingURL=babylon.light.js.map
  21648. var BABYLON;
  21649. (function (BABYLON) {
  21650. var Camera = /** @class */ (function (_super) {
  21651. __extends(Camera, _super);
  21652. function Camera(name, position, scene) {
  21653. var _this = _super.call(this, name, scene) || this;
  21654. /**
  21655. * The vector the camera should consider as up.
  21656. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21657. */
  21658. _this.upVector = BABYLON.Vector3.Up();
  21659. _this.orthoLeft = null;
  21660. _this.orthoRight = null;
  21661. _this.orthoBottom = null;
  21662. _this.orthoTop = null;
  21663. /**
  21664. * FOV is set in Radians. (default is 0.8)
  21665. */
  21666. _this.fov = 0.8;
  21667. _this.minZ = 1;
  21668. _this.maxZ = 10000.0;
  21669. _this.inertia = 0.9;
  21670. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21671. _this.isIntermediate = false;
  21672. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21673. /**
  21674. * Restricts the camera to viewing objects with the same layerMask.
  21675. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21676. */
  21677. _this.layerMask = 0x0FFFFFFF;
  21678. /**
  21679. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21680. */
  21681. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21682. // Camera rig members
  21683. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21684. _this._rigCameras = new Array();
  21685. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21686. _this._skipRendering = false;
  21687. _this.customRenderTargets = new Array();
  21688. // Observables
  21689. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21690. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21691. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21692. _this.onRestoreStateObservable = new BABYLON.Observable();
  21693. // Cache
  21694. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21695. _this._projectionMatrix = new BABYLON.Matrix();
  21696. _this._doNotComputeProjectionMatrix = false;
  21697. _this._postProcesses = new Array();
  21698. _this._transformMatrix = BABYLON.Matrix.Zero();
  21699. _this._activeMeshes = new BABYLON.SmartArray(256);
  21700. _this._globalPosition = BABYLON.Vector3.Zero();
  21701. _this._refreshFrustumPlanes = true;
  21702. _this.getScene().addCamera(_this);
  21703. if (!_this.getScene().activeCamera) {
  21704. _this.getScene().activeCamera = _this;
  21705. }
  21706. _this.position = position;
  21707. return _this;
  21708. }
  21709. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21710. get: function () {
  21711. return Camera._PERSPECTIVE_CAMERA;
  21712. },
  21713. enumerable: true,
  21714. configurable: true
  21715. });
  21716. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21717. get: function () {
  21718. return Camera._ORTHOGRAPHIC_CAMERA;
  21719. },
  21720. enumerable: true,
  21721. configurable: true
  21722. });
  21723. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21724. /**
  21725. * This is the default FOV mode for perspective cameras.
  21726. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21727. *
  21728. */
  21729. get: function () {
  21730. return Camera._FOVMODE_VERTICAL_FIXED;
  21731. },
  21732. enumerable: true,
  21733. configurable: true
  21734. });
  21735. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21736. /**
  21737. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21738. *
  21739. */
  21740. get: function () {
  21741. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21742. },
  21743. enumerable: true,
  21744. configurable: true
  21745. });
  21746. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21747. get: function () {
  21748. return Camera._RIG_MODE_NONE;
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21754. get: function () {
  21755. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21756. },
  21757. enumerable: true,
  21758. configurable: true
  21759. });
  21760. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21761. get: function () {
  21762. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21763. },
  21764. enumerable: true,
  21765. configurable: true
  21766. });
  21767. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21768. get: function () {
  21769. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21770. },
  21771. enumerable: true,
  21772. configurable: true
  21773. });
  21774. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21775. get: function () {
  21776. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21777. },
  21778. enumerable: true,
  21779. configurable: true
  21780. });
  21781. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21782. get: function () {
  21783. return Camera._RIG_MODE_VR;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21789. get: function () {
  21790. return Camera._RIG_MODE_WEBVR;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. /**
  21796. * Store current camera state (fov, position, etc..)
  21797. */
  21798. Camera.prototype.storeState = function () {
  21799. this._stateStored = true;
  21800. this._storedFov = this.fov;
  21801. return this;
  21802. };
  21803. /**
  21804. * Restores the camera state values if it has been stored. You must call storeState() first
  21805. */
  21806. Camera.prototype._restoreStateValues = function () {
  21807. if (!this._stateStored) {
  21808. return false;
  21809. }
  21810. this.fov = this._storedFov;
  21811. return true;
  21812. };
  21813. /**
  21814. * Restored camera state. You must call storeState() first
  21815. */
  21816. Camera.prototype.restoreState = function () {
  21817. if (this._restoreStateValues()) {
  21818. this.onRestoreStateObservable.notifyObservers(this);
  21819. return true;
  21820. }
  21821. return false;
  21822. };
  21823. Camera.prototype.getClassName = function () {
  21824. return "Camera";
  21825. };
  21826. /**
  21827. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21828. */
  21829. Camera.prototype.toString = function (fullDetails) {
  21830. var ret = "Name: " + this.name;
  21831. ret += ", type: " + this.getClassName();
  21832. if (this.animations) {
  21833. for (var i = 0; i < this.animations.length; i++) {
  21834. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21835. }
  21836. }
  21837. if (fullDetails) {
  21838. }
  21839. return ret;
  21840. };
  21841. Object.defineProperty(Camera.prototype, "globalPosition", {
  21842. get: function () {
  21843. return this._globalPosition;
  21844. },
  21845. enumerable: true,
  21846. configurable: true
  21847. });
  21848. Camera.prototype.getActiveMeshes = function () {
  21849. return this._activeMeshes;
  21850. };
  21851. Camera.prototype.isActiveMesh = function (mesh) {
  21852. return (this._activeMeshes.indexOf(mesh) !== -1);
  21853. };
  21854. /**
  21855. * Is this camera ready to be used/rendered
  21856. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21857. * @return true if the camera is ready
  21858. */
  21859. Camera.prototype.isReady = function (completeCheck) {
  21860. if (completeCheck === void 0) { completeCheck = false; }
  21861. if (completeCheck) {
  21862. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21863. var pp = _a[_i];
  21864. if (pp && !pp.isReady()) {
  21865. return false;
  21866. }
  21867. }
  21868. }
  21869. return _super.prototype.isReady.call(this, completeCheck);
  21870. };
  21871. //Cache
  21872. Camera.prototype._initCache = function () {
  21873. _super.prototype._initCache.call(this);
  21874. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21875. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21876. this._cache.mode = undefined;
  21877. this._cache.minZ = undefined;
  21878. this._cache.maxZ = undefined;
  21879. this._cache.fov = undefined;
  21880. this._cache.fovMode = undefined;
  21881. this._cache.aspectRatio = undefined;
  21882. this._cache.orthoLeft = undefined;
  21883. this._cache.orthoRight = undefined;
  21884. this._cache.orthoBottom = undefined;
  21885. this._cache.orthoTop = undefined;
  21886. this._cache.renderWidth = undefined;
  21887. this._cache.renderHeight = undefined;
  21888. };
  21889. Camera.prototype._updateCache = function (ignoreParentClass) {
  21890. if (!ignoreParentClass) {
  21891. _super.prototype._updateCache.call(this);
  21892. }
  21893. this._cache.position.copyFrom(this.position);
  21894. this._cache.upVector.copyFrom(this.upVector);
  21895. };
  21896. // Synchronized
  21897. Camera.prototype._isSynchronized = function () {
  21898. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  21899. };
  21900. Camera.prototype._isSynchronizedViewMatrix = function () {
  21901. if (!_super.prototype._isSynchronized.call(this))
  21902. return false;
  21903. return this._cache.position.equals(this.position)
  21904. && this._cache.upVector.equals(this.upVector)
  21905. && this.isSynchronizedWithParent();
  21906. };
  21907. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  21908. var check = this._cache.mode === this.mode
  21909. && this._cache.minZ === this.minZ
  21910. && this._cache.maxZ === this.maxZ;
  21911. if (!check) {
  21912. return false;
  21913. }
  21914. var engine = this.getEngine();
  21915. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  21916. check = this._cache.fov === this.fov
  21917. && this._cache.fovMode === this.fovMode
  21918. && this._cache.aspectRatio === engine.getAspectRatio(this);
  21919. }
  21920. else {
  21921. check = this._cache.orthoLeft === this.orthoLeft
  21922. && this._cache.orthoRight === this.orthoRight
  21923. && this._cache.orthoBottom === this.orthoBottom
  21924. && this._cache.orthoTop === this.orthoTop
  21925. && this._cache.renderWidth === engine.getRenderWidth()
  21926. && this._cache.renderHeight === engine.getRenderHeight();
  21927. }
  21928. return check;
  21929. };
  21930. // Controls
  21931. Camera.prototype.attachControl = function (element, noPreventDefault) {
  21932. };
  21933. Camera.prototype.detachControl = function (element) {
  21934. };
  21935. Camera.prototype.update = function () {
  21936. this._checkInputs();
  21937. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  21938. this._updateRigCameras();
  21939. }
  21940. };
  21941. Camera.prototype._checkInputs = function () {
  21942. this.onAfterCheckInputsObservable.notifyObservers(this);
  21943. };
  21944. Object.defineProperty(Camera.prototype, "rigCameras", {
  21945. get: function () {
  21946. return this._rigCameras;
  21947. },
  21948. enumerable: true,
  21949. configurable: true
  21950. });
  21951. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  21952. get: function () {
  21953. return this._rigPostProcess;
  21954. },
  21955. enumerable: true,
  21956. configurable: true
  21957. });
  21958. /**
  21959. * Internal, gets the first post proces.
  21960. * @returns the first post process to be run on this camera.
  21961. */
  21962. Camera.prototype._getFirstPostProcess = function () {
  21963. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  21964. if (this._postProcesses[ppIndex] !== null) {
  21965. return this._postProcesses[ppIndex];
  21966. }
  21967. }
  21968. return null;
  21969. };
  21970. Camera.prototype._cascadePostProcessesToRigCams = function () {
  21971. // invalidate framebuffer
  21972. var firstPostProcess = this._getFirstPostProcess();
  21973. if (firstPostProcess) {
  21974. firstPostProcess.markTextureDirty();
  21975. }
  21976. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  21977. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  21978. var cam = this._rigCameras[i];
  21979. var rigPostProcess = cam._rigPostProcess;
  21980. // for VR rig, there does not have to be a post process
  21981. if (rigPostProcess) {
  21982. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  21983. if (isPass) {
  21984. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  21985. cam.isIntermediate = this._postProcesses.length === 0;
  21986. }
  21987. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  21988. rigPostProcess.markTextureDirty();
  21989. }
  21990. else {
  21991. cam._postProcesses = this._postProcesses.slice(0);
  21992. }
  21993. }
  21994. };
  21995. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  21996. if (insertAt === void 0) { insertAt = null; }
  21997. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  21998. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  21999. return 0;
  22000. }
  22001. if (insertAt == null || insertAt < 0) {
  22002. this._postProcesses.push(postProcess);
  22003. }
  22004. else if (this._postProcesses[insertAt] === null) {
  22005. this._postProcesses[insertAt] = postProcess;
  22006. }
  22007. else {
  22008. this._postProcesses.splice(insertAt, 0, postProcess);
  22009. }
  22010. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22011. return this._postProcesses.indexOf(postProcess);
  22012. };
  22013. Camera.prototype.detachPostProcess = function (postProcess) {
  22014. var idx = this._postProcesses.indexOf(postProcess);
  22015. if (idx !== -1) {
  22016. this._postProcesses[idx] = null;
  22017. }
  22018. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22019. };
  22020. Camera.prototype.getWorldMatrix = function () {
  22021. if (!this._worldMatrix) {
  22022. this._worldMatrix = BABYLON.Matrix.Identity();
  22023. }
  22024. var viewMatrix = this.getViewMatrix();
  22025. viewMatrix.invertToRef(this._worldMatrix);
  22026. return this._worldMatrix;
  22027. };
  22028. Camera.prototype._getViewMatrix = function () {
  22029. return BABYLON.Matrix.Identity();
  22030. };
  22031. Camera.prototype.getViewMatrix = function (force) {
  22032. if (!force && this._isSynchronizedViewMatrix()) {
  22033. return this._computedViewMatrix;
  22034. }
  22035. this.updateCache();
  22036. this._computedViewMatrix = this._getViewMatrix();
  22037. this._currentRenderId = this.getScene().getRenderId();
  22038. this._childRenderId = this._currentRenderId;
  22039. this._refreshFrustumPlanes = true;
  22040. if (!this.parent || !this.parent.getWorldMatrix) {
  22041. this._globalPosition.copyFrom(this.position);
  22042. }
  22043. else {
  22044. if (!this._worldMatrix) {
  22045. this._worldMatrix = BABYLON.Matrix.Identity();
  22046. }
  22047. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22048. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22049. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22050. this._computedViewMatrix.invert();
  22051. this._markSyncedWithParent();
  22052. }
  22053. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22054. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22055. }
  22056. this.onViewMatrixChangedObservable.notifyObservers(this);
  22057. return this._computedViewMatrix;
  22058. };
  22059. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22060. this._doNotComputeProjectionMatrix = true;
  22061. if (projection !== undefined) {
  22062. this._projectionMatrix = projection;
  22063. }
  22064. };
  22065. ;
  22066. Camera.prototype.unfreezeProjectionMatrix = function () {
  22067. this._doNotComputeProjectionMatrix = false;
  22068. };
  22069. ;
  22070. Camera.prototype.getProjectionMatrix = function (force) {
  22071. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22072. return this._projectionMatrix;
  22073. }
  22074. // Cache
  22075. this._cache.mode = this.mode;
  22076. this._cache.minZ = this.minZ;
  22077. this._cache.maxZ = this.maxZ;
  22078. // Matrix
  22079. this._refreshFrustumPlanes = true;
  22080. var engine = this.getEngine();
  22081. var scene = this.getScene();
  22082. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22083. this._cache.fov = this.fov;
  22084. this._cache.fovMode = this.fovMode;
  22085. this._cache.aspectRatio = engine.getAspectRatio(this);
  22086. if (this.minZ <= 0) {
  22087. this.minZ = 0.1;
  22088. }
  22089. if (scene.useRightHandedSystem) {
  22090. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22091. }
  22092. else {
  22093. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22094. }
  22095. }
  22096. else {
  22097. var halfWidth = engine.getRenderWidth() / 2.0;
  22098. var halfHeight = engine.getRenderHeight() / 2.0;
  22099. if (scene.useRightHandedSystem) {
  22100. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22101. }
  22102. else {
  22103. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22104. }
  22105. this._cache.orthoLeft = this.orthoLeft;
  22106. this._cache.orthoRight = this.orthoRight;
  22107. this._cache.orthoBottom = this.orthoBottom;
  22108. this._cache.orthoTop = this.orthoTop;
  22109. this._cache.renderWidth = engine.getRenderWidth();
  22110. this._cache.renderHeight = engine.getRenderHeight();
  22111. }
  22112. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22113. return this._projectionMatrix;
  22114. };
  22115. Camera.prototype.getTranformationMatrix = function () {
  22116. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22117. return this._transformMatrix;
  22118. };
  22119. Camera.prototype.updateFrustumPlanes = function () {
  22120. if (!this._refreshFrustumPlanes) {
  22121. return;
  22122. }
  22123. this.getTranformationMatrix();
  22124. if (!this._frustumPlanes) {
  22125. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22126. }
  22127. else {
  22128. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22129. }
  22130. this._refreshFrustumPlanes = false;
  22131. };
  22132. Camera.prototype.isInFrustum = function (target) {
  22133. this.updateFrustumPlanes();
  22134. return target.isInFrustum(this._frustumPlanes);
  22135. };
  22136. Camera.prototype.isCompletelyInFrustum = function (target) {
  22137. this.updateFrustumPlanes();
  22138. return target.isCompletelyInFrustum(this._frustumPlanes);
  22139. };
  22140. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22141. if (length === void 0) { length = 100; }
  22142. if (!transform) {
  22143. transform = this.getWorldMatrix();
  22144. }
  22145. if (!origin) {
  22146. origin = this.position;
  22147. }
  22148. var forward = new BABYLON.Vector3(0, 0, 1);
  22149. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22150. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22151. return new BABYLON.Ray(origin, direction, length);
  22152. };
  22153. /**
  22154. * Releases resources associated with this node.
  22155. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22156. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22157. */
  22158. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22159. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22160. // Observables
  22161. this.onViewMatrixChangedObservable.clear();
  22162. this.onProjectionMatrixChangedObservable.clear();
  22163. this.onAfterCheckInputsObservable.clear();
  22164. this.onRestoreStateObservable.clear();
  22165. // Inputs
  22166. if (this.inputs) {
  22167. this.inputs.clear();
  22168. }
  22169. // Animations
  22170. this.getScene().stopAnimation(this);
  22171. // Remove from scene
  22172. this.getScene().removeCamera(this);
  22173. while (this._rigCameras.length > 0) {
  22174. var camera = this._rigCameras.pop();
  22175. if (camera) {
  22176. camera.dispose();
  22177. }
  22178. }
  22179. // Postprocesses
  22180. if (this._rigPostProcess) {
  22181. this._rigPostProcess.dispose(this);
  22182. this._rigPostProcess = null;
  22183. this._postProcesses = [];
  22184. }
  22185. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22186. this._rigPostProcess = null;
  22187. this._postProcesses = [];
  22188. }
  22189. else {
  22190. var i = this._postProcesses.length;
  22191. while (--i >= 0) {
  22192. var postProcess = this._postProcesses[i];
  22193. if (postProcess) {
  22194. postProcess.dispose(this);
  22195. }
  22196. }
  22197. }
  22198. // Render targets
  22199. var i = this.customRenderTargets.length;
  22200. while (--i >= 0) {
  22201. this.customRenderTargets[i].dispose();
  22202. }
  22203. this.customRenderTargets = [];
  22204. // Active Meshes
  22205. this._activeMeshes.dispose();
  22206. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22207. };
  22208. Object.defineProperty(Camera.prototype, "leftCamera", {
  22209. // ---- Camera rigs section ----
  22210. get: function () {
  22211. if (this._rigCameras.length < 1) {
  22212. return null;
  22213. }
  22214. return this._rigCameras[0];
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera.prototype, "rightCamera", {
  22220. get: function () {
  22221. if (this._rigCameras.length < 2) {
  22222. return null;
  22223. }
  22224. return this._rigCameras[1];
  22225. },
  22226. enumerable: true,
  22227. configurable: true
  22228. });
  22229. Camera.prototype.getLeftTarget = function () {
  22230. if (this._rigCameras.length < 1) {
  22231. return null;
  22232. }
  22233. return this._rigCameras[0].getTarget();
  22234. };
  22235. Camera.prototype.getRightTarget = function () {
  22236. if (this._rigCameras.length < 2) {
  22237. return null;
  22238. }
  22239. return this._rigCameras[1].getTarget();
  22240. };
  22241. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22242. if (this.cameraRigMode === mode) {
  22243. return;
  22244. }
  22245. while (this._rigCameras.length > 0) {
  22246. var camera = this._rigCameras.pop();
  22247. if (camera) {
  22248. camera.dispose();
  22249. }
  22250. }
  22251. this.cameraRigMode = mode;
  22252. this._cameraRigParams = {};
  22253. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22254. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22255. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22256. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22257. // create the rig cameras, unless none
  22258. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22259. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22260. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22261. if (leftCamera && rightCamera) {
  22262. this._rigCameras.push(leftCamera);
  22263. this._rigCameras.push(rightCamera);
  22264. }
  22265. }
  22266. switch (this.cameraRigMode) {
  22267. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22268. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22269. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22270. break;
  22271. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22272. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22273. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22274. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22275. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22276. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22277. break;
  22278. case Camera.RIG_MODE_VR:
  22279. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22280. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22281. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22282. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22283. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22284. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22285. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22286. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22287. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22288. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22289. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22290. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22291. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22292. if (metrics.compensateDistortion) {
  22293. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22294. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22295. }
  22296. break;
  22297. case Camera.RIG_MODE_WEBVR:
  22298. if (rigParams.vrDisplay) {
  22299. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22300. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22301. //Left eye
  22302. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22303. this._rigCameras[0].setCameraRigParameter("left", true);
  22304. //leaving this for future reference
  22305. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22306. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22307. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22308. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22309. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22310. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22311. this._rigCameras[0].parent = this;
  22312. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22313. //Right eye
  22314. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22315. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22316. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22317. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22318. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22319. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22320. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22321. this._rigCameras[1].parent = this;
  22322. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22323. if (Camera.UseAlternateWebVRRendering) {
  22324. this._rigCameras[1]._skipRendering = true;
  22325. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22326. }
  22327. }
  22328. break;
  22329. }
  22330. this._cascadePostProcessesToRigCams();
  22331. this.update();
  22332. };
  22333. Camera.prototype._getVRProjectionMatrix = function () {
  22334. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22335. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22336. return this._projectionMatrix;
  22337. };
  22338. Camera.prototype._updateCameraRotationMatrix = function () {
  22339. //Here for WebVR
  22340. };
  22341. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22342. //Here for WebVR
  22343. };
  22344. /**
  22345. * This function MUST be overwritten by the different WebVR cameras available.
  22346. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22347. */
  22348. Camera.prototype._getWebVRProjectionMatrix = function () {
  22349. return BABYLON.Matrix.Identity();
  22350. };
  22351. /**
  22352. * This function MUST be overwritten by the different WebVR cameras available.
  22353. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22354. */
  22355. Camera.prototype._getWebVRViewMatrix = function () {
  22356. return BABYLON.Matrix.Identity();
  22357. };
  22358. Camera.prototype.setCameraRigParameter = function (name, value) {
  22359. if (!this._cameraRigParams) {
  22360. this._cameraRigParams = {};
  22361. }
  22362. this._cameraRigParams[name] = value;
  22363. //provisionnally:
  22364. if (name === "interaxialDistance") {
  22365. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22366. }
  22367. };
  22368. /**
  22369. * needs to be overridden by children so sub has required properties to be copied
  22370. */
  22371. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22372. return null;
  22373. };
  22374. /**
  22375. * May need to be overridden by children
  22376. */
  22377. Camera.prototype._updateRigCameras = function () {
  22378. for (var i = 0; i < this._rigCameras.length; i++) {
  22379. this._rigCameras[i].minZ = this.minZ;
  22380. this._rigCameras[i].maxZ = this.maxZ;
  22381. this._rigCameras[i].fov = this.fov;
  22382. }
  22383. // only update viewport when ANAGLYPH
  22384. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22385. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22386. }
  22387. };
  22388. Camera.prototype._setupInputs = function () {
  22389. };
  22390. Camera.prototype.serialize = function () {
  22391. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22392. // Type
  22393. serializationObject.type = this.getClassName();
  22394. // Parent
  22395. if (this.parent) {
  22396. serializationObject.parentId = this.parent.id;
  22397. }
  22398. if (this.inputs) {
  22399. this.inputs.serialize(serializationObject);
  22400. }
  22401. // Animations
  22402. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22403. serializationObject.ranges = this.serializeAnimationRanges();
  22404. return serializationObject;
  22405. };
  22406. Camera.prototype.clone = function (name) {
  22407. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22408. };
  22409. Camera.prototype.getDirection = function (localAxis) {
  22410. var result = BABYLON.Vector3.Zero();
  22411. this.getDirectionToRef(localAxis, result);
  22412. return result;
  22413. };
  22414. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22415. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22416. };
  22417. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22418. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22419. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22420. switch (type) {
  22421. case "ArcRotateCamera":
  22422. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22423. case "DeviceOrientationCamera":
  22424. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22425. case "FollowCamera":
  22426. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22427. case "ArcFollowCamera":
  22428. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22429. case "GamepadCamera":
  22430. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22431. case "TouchCamera":
  22432. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22433. case "VirtualJoysticksCamera":
  22434. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22435. case "WebVRFreeCamera":
  22436. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22437. case "WebVRGamepadCamera":
  22438. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22439. case "VRDeviceOrientationFreeCamera":
  22440. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22441. case "VRDeviceOrientationGamepadCamera":
  22442. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22443. case "AnaglyphArcRotateCamera":
  22444. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22445. case "AnaglyphFreeCamera":
  22446. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22447. case "AnaglyphGamepadCamera":
  22448. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22449. case "AnaglyphUniversalCamera":
  22450. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22451. case "StereoscopicArcRotateCamera":
  22452. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22453. case "StereoscopicFreeCamera":
  22454. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22455. case "StereoscopicGamepadCamera":
  22456. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22457. case "StereoscopicUniversalCamera":
  22458. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22459. case "FreeCamera": // Forcing Universal here
  22460. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22461. default: // Universal Camera is the default value
  22462. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22463. }
  22464. };
  22465. Camera.prototype.computeWorldMatrix = function () {
  22466. return this.getWorldMatrix();
  22467. };
  22468. Camera.Parse = function (parsedCamera, scene) {
  22469. var type = parsedCamera.type;
  22470. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22471. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22472. // Parent
  22473. if (parsedCamera.parentId) {
  22474. camera._waitingParentId = parsedCamera.parentId;
  22475. }
  22476. //If camera has an input manager, let it parse inputs settings
  22477. if (camera.inputs) {
  22478. camera.inputs.parse(parsedCamera);
  22479. camera._setupInputs();
  22480. }
  22481. if (camera.setPosition) { // need to force position
  22482. camera.position.copyFromFloats(0, 0, 0);
  22483. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22484. }
  22485. // Target
  22486. if (parsedCamera.target) {
  22487. if (camera.setTarget) {
  22488. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22489. }
  22490. }
  22491. // Apply 3d rig, when found
  22492. if (parsedCamera.cameraRigMode) {
  22493. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22494. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22495. }
  22496. // Animations
  22497. if (parsedCamera.animations) {
  22498. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22499. var parsedAnimation = parsedCamera.animations[animationIndex];
  22500. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22501. }
  22502. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22503. }
  22504. if (parsedCamera.autoAnimate) {
  22505. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22506. }
  22507. return camera;
  22508. };
  22509. // Statics
  22510. Camera._PERSPECTIVE_CAMERA = 0;
  22511. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22512. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22513. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22514. Camera._RIG_MODE_NONE = 0;
  22515. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22516. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22517. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22518. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22519. Camera._RIG_MODE_VR = 20;
  22520. Camera._RIG_MODE_WEBVR = 21;
  22521. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22522. Camera.UseAlternateWebVRRendering = false;
  22523. __decorate([
  22524. BABYLON.serializeAsVector3()
  22525. ], Camera.prototype, "position", void 0);
  22526. __decorate([
  22527. BABYLON.serializeAsVector3()
  22528. ], Camera.prototype, "upVector", void 0);
  22529. __decorate([
  22530. BABYLON.serialize()
  22531. ], Camera.prototype, "orthoLeft", void 0);
  22532. __decorate([
  22533. BABYLON.serialize()
  22534. ], Camera.prototype, "orthoRight", void 0);
  22535. __decorate([
  22536. BABYLON.serialize()
  22537. ], Camera.prototype, "orthoBottom", void 0);
  22538. __decorate([
  22539. BABYLON.serialize()
  22540. ], Camera.prototype, "orthoTop", void 0);
  22541. __decorate([
  22542. BABYLON.serialize()
  22543. ], Camera.prototype, "fov", void 0);
  22544. __decorate([
  22545. BABYLON.serialize()
  22546. ], Camera.prototype, "minZ", void 0);
  22547. __decorate([
  22548. BABYLON.serialize()
  22549. ], Camera.prototype, "maxZ", void 0);
  22550. __decorate([
  22551. BABYLON.serialize()
  22552. ], Camera.prototype, "inertia", void 0);
  22553. __decorate([
  22554. BABYLON.serialize()
  22555. ], Camera.prototype, "mode", void 0);
  22556. __decorate([
  22557. BABYLON.serialize()
  22558. ], Camera.prototype, "layerMask", void 0);
  22559. __decorate([
  22560. BABYLON.serialize()
  22561. ], Camera.prototype, "fovMode", void 0);
  22562. __decorate([
  22563. BABYLON.serialize()
  22564. ], Camera.prototype, "cameraRigMode", void 0);
  22565. __decorate([
  22566. BABYLON.serialize()
  22567. ], Camera.prototype, "interaxialDistance", void 0);
  22568. __decorate([
  22569. BABYLON.serialize()
  22570. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22571. return Camera;
  22572. }(BABYLON.Node));
  22573. BABYLON.Camera = Camera;
  22574. })(BABYLON || (BABYLON = {}));
  22575. //# sourceMappingURL=babylon.camera.js.map
  22576. var BABYLON;
  22577. (function (BABYLON) {
  22578. var RenderingManager = /** @class */ (function () {
  22579. function RenderingManager(scene) {
  22580. this._renderingGroups = new Array();
  22581. this._autoClearDepthStencil = {};
  22582. this._customOpaqueSortCompareFn = {};
  22583. this._customAlphaTestSortCompareFn = {};
  22584. this._customTransparentSortCompareFn = {};
  22585. this._renderinGroupInfo = null;
  22586. this._scene = scene;
  22587. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22588. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22589. }
  22590. }
  22591. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22592. if (depth === void 0) { depth = true; }
  22593. if (stencil === void 0) { stencil = true; }
  22594. if (this._depthStencilBufferAlreadyCleaned) {
  22595. return;
  22596. }
  22597. this._scene.getEngine().clear(null, false, depth, stencil);
  22598. this._depthStencilBufferAlreadyCleaned = true;
  22599. };
  22600. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22601. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22602. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22603. var info = null;
  22604. if (observable) {
  22605. if (!this._renderinGroupInfo) {
  22606. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22607. }
  22608. info = this._renderinGroupInfo;
  22609. info.scene = this._scene;
  22610. info.camera = this._scene.activeCamera;
  22611. }
  22612. // Dispatch sprites
  22613. if (renderSprites) {
  22614. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22615. var manager = this._scene.spriteManagers[index];
  22616. this.dispatchSprites(manager);
  22617. }
  22618. }
  22619. // Render
  22620. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22621. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22622. var renderingGroup = this._renderingGroups[index];
  22623. if (!renderingGroup && !observable)
  22624. continue;
  22625. var renderingGroupMask = 0;
  22626. // Fire PRECLEAR stage
  22627. if (observable && info) {
  22628. renderingGroupMask = Math.pow(2, index);
  22629. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22630. info.renderingGroupId = index;
  22631. observable.notifyObservers(info, renderingGroupMask);
  22632. }
  22633. // Clear depth/stencil if needed
  22634. if (RenderingManager.AUTOCLEAR) {
  22635. var autoClear = this._autoClearDepthStencil[index];
  22636. if (autoClear && autoClear.autoClear) {
  22637. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22638. }
  22639. }
  22640. if (observable && info) {
  22641. // Fire PREOPAQUE stage
  22642. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22643. observable.notifyObservers(info, renderingGroupMask);
  22644. // Fire PRETRANSPARENT stage
  22645. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22646. observable.notifyObservers(info, renderingGroupMask);
  22647. }
  22648. if (renderingGroup)
  22649. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22650. // Fire POSTTRANSPARENT stage
  22651. if (observable && info) {
  22652. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22653. observable.notifyObservers(info, renderingGroupMask);
  22654. }
  22655. }
  22656. };
  22657. RenderingManager.prototype.reset = function () {
  22658. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22659. var renderingGroup = this._renderingGroups[index];
  22660. if (renderingGroup) {
  22661. renderingGroup.prepare();
  22662. }
  22663. }
  22664. };
  22665. RenderingManager.prototype.dispose = function () {
  22666. this.freeRenderingGroups();
  22667. this._renderingGroups.length = 0;
  22668. };
  22669. /**
  22670. * Clear the info related to rendering groups preventing retention points during dispose.
  22671. */
  22672. RenderingManager.prototype.freeRenderingGroups = function () {
  22673. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22674. var renderingGroup = this._renderingGroups[index];
  22675. if (renderingGroup) {
  22676. renderingGroup.dispose();
  22677. }
  22678. }
  22679. };
  22680. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22681. if (this._renderingGroups[renderingGroupId] === undefined) {
  22682. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22683. }
  22684. };
  22685. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22686. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22687. this._prepareRenderingGroup(renderingGroupId);
  22688. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22689. };
  22690. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22691. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22692. this._prepareRenderingGroup(renderingGroupId);
  22693. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22694. };
  22695. /**
  22696. * @param subMesh The submesh to dispatch
  22697. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22698. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22699. */
  22700. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22701. if (mesh === undefined) {
  22702. mesh = subMesh.getMesh();
  22703. }
  22704. var renderingGroupId = mesh.renderingGroupId || 0;
  22705. this._prepareRenderingGroup(renderingGroupId);
  22706. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22707. };
  22708. /**
  22709. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22710. * This allowed control for front to back rendering or reversly depending of the special needs.
  22711. *
  22712. * @param renderingGroupId The rendering group id corresponding to its index
  22713. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22714. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22715. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22716. */
  22717. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22718. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22719. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22720. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22721. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22722. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22723. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22724. if (this._renderingGroups[renderingGroupId]) {
  22725. var group = this._renderingGroups[renderingGroupId];
  22726. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22727. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22728. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22729. }
  22730. };
  22731. /**
  22732. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22733. *
  22734. * @param renderingGroupId The rendering group id corresponding to its index
  22735. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22736. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22737. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22738. */
  22739. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22740. if (depth === void 0) { depth = true; }
  22741. if (stencil === void 0) { stencil = true; }
  22742. this._autoClearDepthStencil[renderingGroupId] = {
  22743. autoClear: autoClearDepthStencil,
  22744. depth: depth,
  22745. stencil: stencil
  22746. };
  22747. };
  22748. /**
  22749. * The max id used for rendering groups (not included)
  22750. */
  22751. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22752. /**
  22753. * The min id used for rendering groups (included)
  22754. */
  22755. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22756. /**
  22757. * Used to globally prevent autoclearing scenes.
  22758. */
  22759. RenderingManager.AUTOCLEAR = true;
  22760. return RenderingManager;
  22761. }());
  22762. BABYLON.RenderingManager = RenderingManager;
  22763. })(BABYLON || (BABYLON = {}));
  22764. //# sourceMappingURL=babylon.renderingManager.js.map
  22765. var BABYLON;
  22766. (function (BABYLON) {
  22767. var RenderingGroup = /** @class */ (function () {
  22768. /**
  22769. * Creates a new rendering group.
  22770. * @param index The rendering group index
  22771. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22772. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22773. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22774. */
  22775. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22776. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22777. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22778. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22779. this.index = index;
  22780. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22781. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22782. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22783. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22784. this._particleSystems = new BABYLON.SmartArray(256);
  22785. this._spriteManagers = new BABYLON.SmartArray(256);
  22786. this._edgesRenderers = new BABYLON.SmartArray(16);
  22787. this._scene = scene;
  22788. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22789. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22790. this.transparentSortCompareFn = transparentSortCompareFn;
  22791. }
  22792. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22793. /**
  22794. * Set the opaque sort comparison function.
  22795. * If null the sub meshes will be render in the order they were created
  22796. */
  22797. set: function (value) {
  22798. this._opaqueSortCompareFn = value;
  22799. if (value) {
  22800. this._renderOpaque = this.renderOpaqueSorted;
  22801. }
  22802. else {
  22803. this._renderOpaque = RenderingGroup.renderUnsorted;
  22804. }
  22805. },
  22806. enumerable: true,
  22807. configurable: true
  22808. });
  22809. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22810. /**
  22811. * Set the alpha test sort comparison function.
  22812. * If null the sub meshes will be render in the order they were created
  22813. */
  22814. set: function (value) {
  22815. this._alphaTestSortCompareFn = value;
  22816. if (value) {
  22817. this._renderAlphaTest = this.renderAlphaTestSorted;
  22818. }
  22819. else {
  22820. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22821. }
  22822. },
  22823. enumerable: true,
  22824. configurable: true
  22825. });
  22826. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22827. /**
  22828. * Set the transparent sort comparison function.
  22829. * If null the sub meshes will be render in the order they were created
  22830. */
  22831. set: function (value) {
  22832. if (value) {
  22833. this._transparentSortCompareFn = value;
  22834. }
  22835. else {
  22836. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22837. }
  22838. this._renderTransparent = this.renderTransparentSorted;
  22839. },
  22840. enumerable: true,
  22841. configurable: true
  22842. });
  22843. /**
  22844. * Render all the sub meshes contained in the group.
  22845. * @param customRenderFunction Used to override the default render behaviour of the group.
  22846. * @returns true if rendered some submeshes.
  22847. */
  22848. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22849. if (customRenderFunction) {
  22850. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22851. return;
  22852. }
  22853. var engine = this._scene.getEngine();
  22854. // Depth only
  22855. if (this._depthOnlySubMeshes.length !== 0) {
  22856. engine.setColorWrite(false);
  22857. this._renderAlphaTest(this._depthOnlySubMeshes);
  22858. engine.setColorWrite(true);
  22859. }
  22860. // Opaque
  22861. if (this._opaqueSubMeshes.length !== 0) {
  22862. this._renderOpaque(this._opaqueSubMeshes);
  22863. }
  22864. // Alpha test
  22865. if (this._alphaTestSubMeshes.length !== 0) {
  22866. this._renderAlphaTest(this._alphaTestSubMeshes);
  22867. }
  22868. var stencilState = engine.getStencilBuffer();
  22869. engine.setStencilBuffer(false);
  22870. // Sprites
  22871. if (renderSprites) {
  22872. this._renderSprites();
  22873. }
  22874. // Particles
  22875. if (renderParticles) {
  22876. this._renderParticles(activeMeshes);
  22877. }
  22878. if (this.onBeforeTransparentRendering) {
  22879. this.onBeforeTransparentRendering();
  22880. }
  22881. // Transparent
  22882. if (this._transparentSubMeshes.length !== 0) {
  22883. this._renderTransparent(this._transparentSubMeshes);
  22884. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22885. }
  22886. // Set back stencil to false in case it changes before the edge renderer.
  22887. engine.setStencilBuffer(false);
  22888. // Edges
  22889. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  22890. this._edgesRenderers.data[edgesRendererIndex].render();
  22891. }
  22892. // Restore Stencil state.
  22893. engine.setStencilBuffer(stencilState);
  22894. };
  22895. /**
  22896. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  22897. * @param subMeshes The submeshes to render
  22898. */
  22899. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  22900. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  22901. };
  22902. /**
  22903. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  22904. * @param subMeshes The submeshes to render
  22905. */
  22906. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  22907. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  22908. };
  22909. /**
  22910. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  22911. * @param subMeshes The submeshes to render
  22912. */
  22913. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  22914. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  22915. };
  22916. /**
  22917. * Renders the submeshes in a specified order.
  22918. * @param subMeshes The submeshes to sort before render
  22919. * @param sortCompareFn The comparison function use to sort
  22920. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  22921. * @param transparent Specifies to activate blending if true
  22922. */
  22923. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  22924. var subIndex = 0;
  22925. var subMesh;
  22926. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  22927. for (; subIndex < subMeshes.length; subIndex++) {
  22928. subMesh = subMeshes.data[subIndex];
  22929. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  22930. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  22931. }
  22932. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  22933. if (sortCompareFn) {
  22934. sortedArray.sort(sortCompareFn);
  22935. }
  22936. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  22937. subMesh = sortedArray[subIndex];
  22938. if (transparent) {
  22939. var material = subMesh.getMaterial();
  22940. if (material && material.needDepthPrePass) {
  22941. var engine = material.getScene().getEngine();
  22942. engine.setColorWrite(false);
  22943. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22944. subMesh.render(false);
  22945. engine.setColorWrite(true);
  22946. }
  22947. }
  22948. subMesh.render(transparent);
  22949. }
  22950. };
  22951. /**
  22952. * Renders the submeshes in the order they were dispatched (no sort applied).
  22953. * @param subMeshes The submeshes to render
  22954. */
  22955. RenderingGroup.renderUnsorted = function (subMeshes) {
  22956. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  22957. var submesh = subMeshes.data[subIndex];
  22958. submesh.render(false);
  22959. }
  22960. };
  22961. /**
  22962. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22963. * are rendered back to front if in the same alpha index.
  22964. *
  22965. * @param a The first submesh
  22966. * @param b The second submesh
  22967. * @returns The result of the comparison
  22968. */
  22969. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  22970. // Alpha index first
  22971. if (a._alphaIndex > b._alphaIndex) {
  22972. return 1;
  22973. }
  22974. if (a._alphaIndex < b._alphaIndex) {
  22975. return -1;
  22976. }
  22977. // Then distance to camera
  22978. return RenderingGroup.backToFrontSortCompare(a, b);
  22979. };
  22980. /**
  22981. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  22982. * are rendered back to front.
  22983. *
  22984. * @param a The first submesh
  22985. * @param b The second submesh
  22986. * @returns The result of the comparison
  22987. */
  22988. RenderingGroup.backToFrontSortCompare = function (a, b) {
  22989. // Then distance to camera
  22990. if (a._distanceToCamera < b._distanceToCamera) {
  22991. return 1;
  22992. }
  22993. if (a._distanceToCamera > b._distanceToCamera) {
  22994. return -1;
  22995. }
  22996. return 0;
  22997. };
  22998. /**
  22999. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23000. * are rendered front to back (prevent overdraw).
  23001. *
  23002. * @param a The first submesh
  23003. * @param b The second submesh
  23004. * @returns The result of the comparison
  23005. */
  23006. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23007. // Then distance to camera
  23008. if (a._distanceToCamera < b._distanceToCamera) {
  23009. return -1;
  23010. }
  23011. if (a._distanceToCamera > b._distanceToCamera) {
  23012. return 1;
  23013. }
  23014. return 0;
  23015. };
  23016. /**
  23017. * Resets the different lists of submeshes to prepare a new frame.
  23018. */
  23019. RenderingGroup.prototype.prepare = function () {
  23020. this._opaqueSubMeshes.reset();
  23021. this._transparentSubMeshes.reset();
  23022. this._alphaTestSubMeshes.reset();
  23023. this._depthOnlySubMeshes.reset();
  23024. this._particleSystems.reset();
  23025. this._spriteManagers.reset();
  23026. this._edgesRenderers.reset();
  23027. };
  23028. RenderingGroup.prototype.dispose = function () {
  23029. this._opaqueSubMeshes.dispose();
  23030. this._transparentSubMeshes.dispose();
  23031. this._alphaTestSubMeshes.dispose();
  23032. this._depthOnlySubMeshes.dispose();
  23033. this._particleSystems.dispose();
  23034. this._spriteManagers.dispose();
  23035. this._edgesRenderers.dispose();
  23036. };
  23037. /**
  23038. * Inserts the submesh in its correct queue depending on its material.
  23039. * @param subMesh The submesh to dispatch
  23040. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23041. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23042. */
  23043. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23044. // Get mesh and materials if not provided
  23045. if (mesh === undefined) {
  23046. mesh = subMesh.getMesh();
  23047. }
  23048. if (material === undefined) {
  23049. material = subMesh.getMaterial();
  23050. }
  23051. if (material === null || material === undefined) {
  23052. return;
  23053. }
  23054. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23055. this._transparentSubMeshes.push(subMesh);
  23056. }
  23057. else if (material.needAlphaTesting()) { // Alpha test
  23058. if (material.needDepthPrePass) {
  23059. this._depthOnlySubMeshes.push(subMesh);
  23060. }
  23061. this._alphaTestSubMeshes.push(subMesh);
  23062. }
  23063. else {
  23064. if (material.needDepthPrePass) {
  23065. this._depthOnlySubMeshes.push(subMesh);
  23066. }
  23067. this._opaqueSubMeshes.push(subMesh); // Opaque
  23068. }
  23069. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23070. this._edgesRenderers.push(mesh._edgesRenderer);
  23071. }
  23072. };
  23073. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23074. this._spriteManagers.push(spriteManager);
  23075. };
  23076. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23077. this._particleSystems.push(particleSystem);
  23078. };
  23079. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23080. if (this._particleSystems.length === 0) {
  23081. return;
  23082. }
  23083. // Particles
  23084. var activeCamera = this._scene.activeCamera;
  23085. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23086. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23087. var particleSystem = this._particleSystems.data[particleIndex];
  23088. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23089. continue;
  23090. }
  23091. var emitter = particleSystem.emitter;
  23092. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23093. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23094. }
  23095. }
  23096. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23097. };
  23098. RenderingGroup.prototype._renderSprites = function () {
  23099. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23100. return;
  23101. }
  23102. // Sprites
  23103. var activeCamera = this._scene.activeCamera;
  23104. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23105. for (var id = 0; id < this._spriteManagers.length; id++) {
  23106. var spriteManager = this._spriteManagers.data[id];
  23107. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23108. spriteManager.render();
  23109. }
  23110. }
  23111. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23112. };
  23113. return RenderingGroup;
  23114. }());
  23115. BABYLON.RenderingGroup = RenderingGroup;
  23116. })(BABYLON || (BABYLON = {}));
  23117. //# sourceMappingURL=babylon.renderingGroup.js.map
  23118. var BABYLON;
  23119. (function (BABYLON) {
  23120. /** @ignore */
  23121. var ClickInfo = /** @class */ (function () {
  23122. function ClickInfo() {
  23123. this._singleClick = false;
  23124. this._doubleClick = false;
  23125. this._hasSwiped = false;
  23126. this._ignore = false;
  23127. }
  23128. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23129. get: function () {
  23130. return this._singleClick;
  23131. },
  23132. set: function (b) {
  23133. this._singleClick = b;
  23134. },
  23135. enumerable: true,
  23136. configurable: true
  23137. });
  23138. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23139. get: function () {
  23140. return this._doubleClick;
  23141. },
  23142. set: function (b) {
  23143. this._doubleClick = b;
  23144. },
  23145. enumerable: true,
  23146. configurable: true
  23147. });
  23148. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23149. get: function () {
  23150. return this._hasSwiped;
  23151. },
  23152. set: function (b) {
  23153. this._hasSwiped = b;
  23154. },
  23155. enumerable: true,
  23156. configurable: true
  23157. });
  23158. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23159. get: function () {
  23160. return this._ignore;
  23161. },
  23162. set: function (b) {
  23163. this._ignore = b;
  23164. },
  23165. enumerable: true,
  23166. configurable: true
  23167. });
  23168. return ClickInfo;
  23169. }());
  23170. /**
  23171. * This class is used by the onRenderingGroupObservable
  23172. */
  23173. var RenderingGroupInfo = /** @class */ (function () {
  23174. function RenderingGroupInfo() {
  23175. }
  23176. /**
  23177. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23178. * This stage will be fired no matter what
  23179. */
  23180. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23181. /**
  23182. * Called before opaque object are rendered.
  23183. * This stage will be fired only if there's 3D Opaque content to render
  23184. */
  23185. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23186. /**
  23187. * Called after the opaque objects are rendered and before the transparent ones
  23188. * This stage will be fired only if there's 3D transparent content to render
  23189. */
  23190. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23191. /**
  23192. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23193. * This stage will be fired no matter what
  23194. */
  23195. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23196. return RenderingGroupInfo;
  23197. }());
  23198. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23199. /**
  23200. * Represents a scene to be rendered by the engine.
  23201. * @see http://doc.babylonjs.com/features/scene
  23202. */
  23203. var Scene = /** @class */ (function () {
  23204. /**
  23205. * Creates a new Scene
  23206. * @param engine defines the engine to use to render this scene
  23207. */
  23208. function Scene(engine) {
  23209. // Members
  23210. /**
  23211. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23212. */
  23213. this.autoClear = true;
  23214. /**
  23215. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23216. */
  23217. this.autoClearDepthAndStencil = true;
  23218. /**
  23219. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23220. */
  23221. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23222. /**
  23223. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23224. */
  23225. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23226. this._forceWireframe = false;
  23227. this._forcePointsCloud = false;
  23228. /**
  23229. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23230. */
  23231. this.forceShowBoundingBoxes = false;
  23232. /**
  23233. * Gets or sets a boolean indicating if animations are enabled
  23234. */
  23235. this.animationsEnabled = true;
  23236. this._animationPropertiesOverride = null;
  23237. /**
  23238. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23239. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23240. */
  23241. this.useConstantAnimationDeltaTime = false;
  23242. /**
  23243. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23244. * Please note that it requires to run a ray cast through the scene on every frame
  23245. */
  23246. this.constantlyUpdateMeshUnderPointer = false;
  23247. /**
  23248. * Defines the HTML cursor to use when hovering over interactive elements
  23249. */
  23250. this.hoverCursor = "pointer";
  23251. /**
  23252. * Defines the HTML default cursor to use (empty by default)
  23253. */
  23254. this.defaultCursor = "";
  23255. /**
  23256. * This is used to call preventDefault() on pointer down
  23257. * in order to block unwanted artifacts like system double clicks
  23258. */
  23259. this.preventDefaultOnPointerDown = true;
  23260. // Metadata
  23261. /**
  23262. * Gets or sets user defined metadata
  23263. */
  23264. this.metadata = null;
  23265. /**
  23266. * Use this array to add regular expressions used to disable offline support for specific urls
  23267. */
  23268. this.disableOfflineSupportExceptionRules = new Array();
  23269. /**
  23270. * An event triggered when the scene is disposed.
  23271. */
  23272. this.onDisposeObservable = new BABYLON.Observable();
  23273. this._onDisposeObserver = null;
  23274. /**
  23275. * An event triggered before rendering the scene (right after animations and physics)
  23276. */
  23277. this.onBeforeRenderObservable = new BABYLON.Observable();
  23278. this._onBeforeRenderObserver = null;
  23279. /**
  23280. * An event triggered after rendering the scene
  23281. */
  23282. this.onAfterRenderObservable = new BABYLON.Observable();
  23283. this._onAfterRenderObserver = null;
  23284. /**
  23285. * An event triggered before animating the scene
  23286. */
  23287. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23288. /**
  23289. * An event triggered after animations processing
  23290. */
  23291. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23292. /**
  23293. * An event triggered before draw calls are ready to be sent
  23294. */
  23295. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23296. /**
  23297. * An event triggered after draw calls have been sent
  23298. */
  23299. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23300. /**
  23301. * An event triggered when physic simulation is about to be run
  23302. */
  23303. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23304. /**
  23305. * An event triggered when physic simulation has been done
  23306. */
  23307. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23308. /**
  23309. * An event triggered when the scene is ready
  23310. */
  23311. this.onReadyObservable = new BABYLON.Observable();
  23312. /**
  23313. * An event triggered before rendering a camera
  23314. */
  23315. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23316. this._onBeforeCameraRenderObserver = null;
  23317. /**
  23318. * An event triggered after rendering a camera
  23319. */
  23320. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23321. this._onAfterCameraRenderObserver = null;
  23322. /**
  23323. * An event triggered when active meshes evaluation is about to start
  23324. */
  23325. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23326. /**
  23327. * An event triggered when active meshes evaluation is done
  23328. */
  23329. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23330. /**
  23331. * An event triggered when particles rendering is about to start
  23332. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23333. */
  23334. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23335. /**
  23336. * An event triggered when particles rendering is done
  23337. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23338. */
  23339. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23340. /**
  23341. * An event triggered when sprites rendering is about to start
  23342. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23343. */
  23344. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23345. /**
  23346. * An event triggered when sprites rendering is done
  23347. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23348. */
  23349. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23350. /**
  23351. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23352. */
  23353. this.onDataLoadedObservable = new BABYLON.Observable();
  23354. /**
  23355. * An event triggered when a camera is created
  23356. */
  23357. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23358. /**
  23359. * An event triggered when a camera is removed
  23360. */
  23361. this.onCameraRemovedObservable = new BABYLON.Observable();
  23362. /**
  23363. * An event triggered when a light is created
  23364. */
  23365. this.onNewLightAddedObservable = new BABYLON.Observable();
  23366. /**
  23367. * An event triggered when a light is removed
  23368. */
  23369. this.onLightRemovedObservable = new BABYLON.Observable();
  23370. /**
  23371. * An event triggered when a geometry is created
  23372. */
  23373. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23374. /**
  23375. * An event triggered when a geometry is removed
  23376. */
  23377. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23378. /**
  23379. * An event triggered when a transform node is created
  23380. */
  23381. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23382. /**
  23383. * An event triggered when a transform node is removed
  23384. */
  23385. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23386. /**
  23387. * An event triggered when a mesh is created
  23388. */
  23389. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23390. /**
  23391. * An event triggered when a mesh is removed
  23392. */
  23393. this.onMeshRemovedObservable = new BABYLON.Observable();
  23394. /**
  23395. * An event triggered when render targets are about to be rendered
  23396. * Can happen multiple times per frame.
  23397. */
  23398. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23399. /**
  23400. * An event triggered when render targets were rendered.
  23401. * Can happen multiple times per frame.
  23402. */
  23403. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23404. /**
  23405. * An event triggered before calculating deterministic simulation step
  23406. */
  23407. this.onBeforeStepObservable = new BABYLON.Observable();
  23408. /**
  23409. * An event triggered after calculating deterministic simulation step
  23410. */
  23411. this.onAfterStepObservable = new BABYLON.Observable();
  23412. /**
  23413. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23414. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23415. * 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)
  23416. */
  23417. this.onRenderingGroupObservable = new BABYLON.Observable();
  23418. // Animations
  23419. /**
  23420. * Gets a list of Animations associated with the scene
  23421. */
  23422. this.animations = [];
  23423. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23424. /**
  23425. * 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).
  23426. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23427. */
  23428. this.onPrePointerObservable = new BABYLON.Observable();
  23429. /**
  23430. * Observable event triggered each time an input event is received from the rendering canvas
  23431. */
  23432. this.onPointerObservable = new BABYLON.Observable();
  23433. this._meshPickProceed = false;
  23434. this._currentPickResult = null;
  23435. this._previousPickResult = null;
  23436. this._totalPointersPressed = 0;
  23437. this._doubleClickOccured = false;
  23438. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23439. this.cameraToUseForPointers = null;
  23440. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23441. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23442. this._startingPointerTime = 0;
  23443. this._previousStartingPointerTime = 0;
  23444. // Deterministic lockstep
  23445. this._timeAccumulator = 0;
  23446. this._currentStepId = 0;
  23447. this._currentInternalStep = 0;
  23448. // Keyboard
  23449. /**
  23450. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23451. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23452. */
  23453. this.onPreKeyboardObservable = new BABYLON.Observable();
  23454. /**
  23455. * Observable event triggered each time an keyboard event is received from the hosting window
  23456. */
  23457. this.onKeyboardObservable = new BABYLON.Observable();
  23458. // Coordinates system
  23459. this._useRightHandedSystem = false;
  23460. // Fog
  23461. this._fogEnabled = true;
  23462. this._fogMode = Scene.FOGMODE_NONE;
  23463. /**
  23464. * Gets or sets the fog color to use
  23465. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23466. */
  23467. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23468. /**
  23469. * Gets or sets the fog density to use
  23470. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23471. */
  23472. this.fogDensity = 0.1;
  23473. /**
  23474. * Gets or sets the fog start distance to use
  23475. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23476. */
  23477. this.fogStart = 0;
  23478. /**
  23479. * Gets or sets the fog end distance to use
  23480. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23481. */
  23482. this.fogEnd = 1000.0;
  23483. // Lights
  23484. this._shadowsEnabled = true;
  23485. this._lightsEnabled = true;
  23486. /**
  23487. * All of the lights added to this scene
  23488. * @see http://doc.babylonjs.com/babylon101/lights
  23489. */
  23490. this.lights = new Array();
  23491. // Cameras
  23492. /** All of the cameras added to this scene.
  23493. * @see http://doc.babylonjs.com/babylon101/cameras
  23494. */
  23495. this.cameras = new Array();
  23496. /** All of the active cameras added to this scene. */
  23497. this.activeCameras = new Array();
  23498. // Meshes
  23499. /**
  23500. * All of the tranform nodes added to this scene
  23501. * @see http://doc.babylonjs.com/how_to/transformnode
  23502. */
  23503. this.transformNodes = new Array();
  23504. /**
  23505. * All of the (abstract) meshes added to this scene
  23506. */
  23507. this.meshes = new Array();
  23508. /**
  23509. * All of the animation groups added to this scene
  23510. * @see http://doc.babylonjs.com/how_to/group
  23511. */
  23512. this.animationGroups = new Array();
  23513. // Geometries
  23514. this._geometries = new Array();
  23515. /**
  23516. * All of the materials added to this scene
  23517. * @see http://doc.babylonjs.com/babylon101/materials
  23518. */
  23519. this.materials = new Array();
  23520. /**
  23521. * All of the multi-materials added to this scene
  23522. * @see http://doc.babylonjs.com/how_to/multi_materials
  23523. */
  23524. this.multiMaterials = new Array();
  23525. // Textures
  23526. this._texturesEnabled = true;
  23527. /**
  23528. * All of the textures added to this scene
  23529. */
  23530. this.textures = new Array();
  23531. // Particles
  23532. /**
  23533. * Gets or sets a boolean indicating if particles are enabled on this scene
  23534. */
  23535. this.particlesEnabled = true;
  23536. /**
  23537. * All of the particle systems added to this scene
  23538. * @see http://doc.babylonjs.com/babylon101/particles
  23539. */
  23540. this.particleSystems = new Array();
  23541. // Sprites
  23542. /**
  23543. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23544. */
  23545. this.spritesEnabled = true;
  23546. /**
  23547. * All of the sprite managers added to this scene
  23548. * @see http://doc.babylonjs.com/babylon101/sprites
  23549. */
  23550. this.spriteManagers = new Array();
  23551. /**
  23552. * The list of layers (background and foreground) of the scene
  23553. */
  23554. this.layers = new Array();
  23555. /**
  23556. * The list of effect layers (highlights/glow) added to the scene
  23557. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23558. * @see http://doc.babylonjs.com/how_to/glow_layer
  23559. */
  23560. this.effectLayers = new Array();
  23561. // Skeletons
  23562. this._skeletonsEnabled = true;
  23563. /**
  23564. * The list of skeletons added to the scene
  23565. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23566. */
  23567. this.skeletons = new Array();
  23568. // Morph targets
  23569. /**
  23570. * The list of morph target managers added to the scene
  23571. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23572. */
  23573. this.morphTargetManagers = new Array();
  23574. // Lens flares
  23575. /**
  23576. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23577. */
  23578. this.lensFlaresEnabled = true;
  23579. /**
  23580. * The list of lens flare system added to the scene
  23581. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23582. */
  23583. this.lensFlareSystems = new Array();
  23584. // Collisions
  23585. /**
  23586. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23587. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23588. */
  23589. this.collisionsEnabled = true;
  23590. /**
  23591. * Defines the gravity applied to this scene (used only for collisions)
  23592. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23593. */
  23594. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23595. // Postprocesses
  23596. /**
  23597. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23598. */
  23599. this.postProcessesEnabled = true;
  23600. /**
  23601. * The list of postprocesses added to the scene
  23602. */
  23603. this.postProcesses = new Array();
  23604. // Customs render targets
  23605. /**
  23606. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23607. */
  23608. this.renderTargetsEnabled = true;
  23609. /**
  23610. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23611. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23612. */
  23613. this.dumpNextRenderTargets = false;
  23614. /**
  23615. * The list of user defined render targets added to the scene
  23616. */
  23617. this.customRenderTargets = new Array();
  23618. /**
  23619. * Gets the list of meshes imported to the scene through SceneLoader
  23620. */
  23621. this.importedMeshesFiles = new Array();
  23622. // Probes
  23623. /**
  23624. * Gets or sets a boolean indicating if probes are enabled on this scene
  23625. */
  23626. this.probesEnabled = true;
  23627. /**
  23628. * The list of reflection probes added to the scene
  23629. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23630. */
  23631. this.reflectionProbes = new Array();
  23632. /** @ignore */
  23633. this._actionManagers = new Array();
  23634. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23635. // Procedural textures
  23636. /**
  23637. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23638. */
  23639. this.proceduralTexturesEnabled = true;
  23640. /**
  23641. * The list of procedural textures added to the scene
  23642. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23643. */
  23644. this.proceduralTextures = new Array();
  23645. /**
  23646. * The list of sound tracks added to the scene
  23647. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23648. */
  23649. this.soundTracks = new Array();
  23650. this._audioEnabled = true;
  23651. this._headphone = false;
  23652. // Performance counters
  23653. this._totalVertices = new BABYLON.PerfCounter();
  23654. /** @ignore */
  23655. this._activeIndices = new BABYLON.PerfCounter();
  23656. /** @ignore */
  23657. this._activeParticles = new BABYLON.PerfCounter();
  23658. /** @ignore */
  23659. this._activeBones = new BABYLON.PerfCounter();
  23660. this._animationTime = 0;
  23661. /**
  23662. * Gets or sets a general scale for animation speed
  23663. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23664. */
  23665. this.animationTimeScale = 1;
  23666. this._renderId = 0;
  23667. this._executeWhenReadyTimeoutId = -1;
  23668. this._intermediateRendering = false;
  23669. this._viewUpdateFlag = -1;
  23670. this._projectionUpdateFlag = -1;
  23671. this._alternateViewUpdateFlag = -1;
  23672. this._alternateProjectionUpdateFlag = -1;
  23673. /** @ignore */
  23674. this._toBeDisposed = new BABYLON.SmartArray(256);
  23675. this._activeRequests = new Array();
  23676. this._pendingData = new Array();
  23677. this._isDisposed = false;
  23678. /**
  23679. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23680. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23681. */
  23682. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23683. this._activeMeshes = new BABYLON.SmartArray(256);
  23684. this._processedMaterials = new BABYLON.SmartArray(256);
  23685. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23686. /** @ignore */
  23687. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23688. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23689. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23690. /** @ignore */
  23691. this._activeAnimatables = new Array();
  23692. this._transformMatrix = BABYLON.Matrix.Zero();
  23693. this._useAlternateCameraConfiguration = false;
  23694. this._alternateRendering = false;
  23695. /**
  23696. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23697. * This is useful if there are more lights that the maximum simulteanous authorized
  23698. */
  23699. this.requireLightSorting = false;
  23700. this._depthRenderer = {};
  23701. this._activeMeshesFrozen = false;
  23702. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23703. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23704. this._engine.scenes.push(this);
  23705. this._uid = null;
  23706. this._renderingManager = new BABYLON.RenderingManager(this);
  23707. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23708. if (BABYLON.OutlineRenderer) {
  23709. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23710. }
  23711. if (BABYLON.Tools.IsWindowObjectExist()) {
  23712. this.attachControl();
  23713. }
  23714. //simplification queue
  23715. if (BABYLON.SimplificationQueue) {
  23716. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23717. }
  23718. //collision coordinator initialization. For now legacy per default.
  23719. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23720. // Uniform Buffer
  23721. this._createUbo();
  23722. // Default Image processing definition.
  23723. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23724. }
  23725. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23726. /** The fog is deactivated */
  23727. get: function () {
  23728. return Scene._FOGMODE_NONE;
  23729. },
  23730. enumerable: true,
  23731. configurable: true
  23732. });
  23733. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23734. /** The fog density is following an exponential function */
  23735. get: function () {
  23736. return Scene._FOGMODE_EXP;
  23737. },
  23738. enumerable: true,
  23739. configurable: true
  23740. });
  23741. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23742. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23743. get: function () {
  23744. return Scene._FOGMODE_EXP2;
  23745. },
  23746. enumerable: true,
  23747. configurable: true
  23748. });
  23749. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23750. /** The fog density is following a linear function. */
  23751. get: function () {
  23752. return Scene._FOGMODE_LINEAR;
  23753. },
  23754. enumerable: true,
  23755. configurable: true
  23756. });
  23757. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23758. /**
  23759. * Texture used in all pbr material as the reflection texture.
  23760. * As in the majority of the scene they are the same (exception for multi room and so on),
  23761. * this is easier to reference from here than from all the materials.
  23762. */
  23763. get: function () {
  23764. return this._environmentTexture;
  23765. },
  23766. /**
  23767. * Texture used in all pbr material as the reflection texture.
  23768. * As in the majority of the scene they are the same (exception for multi room and so on),
  23769. * this is easier to set here than in all the materials.
  23770. */
  23771. set: function (value) {
  23772. if (this._environmentTexture === value) {
  23773. return;
  23774. }
  23775. this._environmentTexture = value;
  23776. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23777. },
  23778. enumerable: true,
  23779. configurable: true
  23780. });
  23781. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23782. /**
  23783. * Default image processing configuration used either in the rendering
  23784. * Forward main pass or through the imageProcessingPostProcess if present.
  23785. * As in the majority of the scene they are the same (exception for multi camera),
  23786. * this is easier to reference from here than from all the materials and post process.
  23787. *
  23788. * No setter as we it is a shared configuration, you can set the values instead.
  23789. */
  23790. get: function () {
  23791. return this._imageProcessingConfiguration;
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23797. get: function () {
  23798. return this._forceWireframe;
  23799. },
  23800. /**
  23801. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23802. */
  23803. set: function (value) {
  23804. if (this._forceWireframe === value) {
  23805. return;
  23806. }
  23807. this._forceWireframe = value;
  23808. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23809. },
  23810. enumerable: true,
  23811. configurable: true
  23812. });
  23813. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23814. get: function () {
  23815. return this._forcePointsCloud;
  23816. },
  23817. /**
  23818. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23819. */
  23820. set: function (value) {
  23821. if (this._forcePointsCloud === value) {
  23822. return;
  23823. }
  23824. this._forcePointsCloud = value;
  23825. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23826. },
  23827. enumerable: true,
  23828. configurable: true
  23829. });
  23830. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23831. /**
  23832. * Gets or sets the animation properties override
  23833. */
  23834. get: function () {
  23835. return this._animationPropertiesOverride;
  23836. },
  23837. set: function (value) {
  23838. this._animationPropertiesOverride = value;
  23839. },
  23840. enumerable: true,
  23841. configurable: true
  23842. });
  23843. Object.defineProperty(Scene.prototype, "onDispose", {
  23844. /** Sets a function to be executed when this scene is disposed. */
  23845. set: function (callback) {
  23846. if (this._onDisposeObserver) {
  23847. this.onDisposeObservable.remove(this._onDisposeObserver);
  23848. }
  23849. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23850. },
  23851. enumerable: true,
  23852. configurable: true
  23853. });
  23854. Object.defineProperty(Scene.prototype, "beforeRender", {
  23855. /** Sets a function to be executed before rendering this scene */
  23856. set: function (callback) {
  23857. if (this._onBeforeRenderObserver) {
  23858. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23859. }
  23860. if (callback) {
  23861. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23862. }
  23863. },
  23864. enumerable: true,
  23865. configurable: true
  23866. });
  23867. Object.defineProperty(Scene.prototype, "afterRender", {
  23868. /** Sets a function to be executed after rendering this scene */
  23869. set: function (callback) {
  23870. if (this._onAfterRenderObserver) {
  23871. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23872. }
  23873. if (callback) {
  23874. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23875. }
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  23881. /** Sets a function to be executed before rendering a camera*/
  23882. set: function (callback) {
  23883. if (this._onBeforeCameraRenderObserver) {
  23884. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  23885. }
  23886. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  23887. },
  23888. enumerable: true,
  23889. configurable: true
  23890. });
  23891. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  23892. /** Sets a function to be executed after rendering a camera*/
  23893. set: function (callback) {
  23894. if (this._onAfterCameraRenderObserver) {
  23895. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  23896. }
  23897. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. Object.defineProperty(Scene.prototype, "gamepadManager", {
  23903. /**
  23904. * Gets the gamepad manager associated with the scene
  23905. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  23906. */
  23907. get: function () {
  23908. if (!this._gamepadManager) {
  23909. this._gamepadManager = new BABYLON.GamepadManager(this);
  23910. }
  23911. return this._gamepadManager;
  23912. },
  23913. enumerable: true,
  23914. configurable: true
  23915. });
  23916. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  23917. /**
  23918. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  23919. */
  23920. get: function () {
  23921. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  23922. },
  23923. enumerable: true,
  23924. configurable: true
  23925. });
  23926. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  23927. get: function () {
  23928. return this._useRightHandedSystem;
  23929. },
  23930. /**
  23931. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  23932. */
  23933. set: function (value) {
  23934. if (this._useRightHandedSystem === value) {
  23935. return;
  23936. }
  23937. this._useRightHandedSystem = value;
  23938. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23939. },
  23940. enumerable: true,
  23941. configurable: true
  23942. });
  23943. /**
  23944. * Sets the step Id used by deterministic lock step
  23945. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23946. * @param newStepId defines the step Id
  23947. */
  23948. Scene.prototype.setStepId = function (newStepId) {
  23949. this._currentStepId = newStepId;
  23950. };
  23951. ;
  23952. /**
  23953. * Gets the step Id used by deterministic lock step
  23954. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23955. * @returns the step Id
  23956. */
  23957. Scene.prototype.getStepId = function () {
  23958. return this._currentStepId;
  23959. };
  23960. ;
  23961. /**
  23962. * Gets the internal step used by deterministic lock step
  23963. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  23964. * @returns the internal step
  23965. */
  23966. Scene.prototype.getInternalStep = function () {
  23967. return this._currentInternalStep;
  23968. };
  23969. ;
  23970. Object.defineProperty(Scene.prototype, "fogEnabled", {
  23971. get: function () {
  23972. return this._fogEnabled;
  23973. },
  23974. /**
  23975. * Gets or sets a boolean indicating if fog is enabled on this scene
  23976. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23977. */
  23978. set: function (value) {
  23979. if (this._fogEnabled === value) {
  23980. return;
  23981. }
  23982. this._fogEnabled = value;
  23983. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23984. },
  23985. enumerable: true,
  23986. configurable: true
  23987. });
  23988. Object.defineProperty(Scene.prototype, "fogMode", {
  23989. get: function () {
  23990. return this._fogMode;
  23991. },
  23992. /**
  23993. * Gets or sets the fog mode to use
  23994. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23995. */
  23996. set: function (value) {
  23997. if (this._fogMode === value) {
  23998. return;
  23999. }
  24000. this._fogMode = value;
  24001. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24002. },
  24003. enumerable: true,
  24004. configurable: true
  24005. });
  24006. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24007. get: function () {
  24008. return this._shadowsEnabled;
  24009. },
  24010. /**
  24011. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24012. */
  24013. set: function (value) {
  24014. if (this._shadowsEnabled === value) {
  24015. return;
  24016. }
  24017. this._shadowsEnabled = value;
  24018. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24024. get: function () {
  24025. return this._lightsEnabled;
  24026. },
  24027. /**
  24028. * Gets or sets a boolean indicating if lights are enabled on this scene
  24029. */
  24030. set: function (value) {
  24031. if (this._lightsEnabled === value) {
  24032. return;
  24033. }
  24034. this._lightsEnabled = value;
  24035. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24036. },
  24037. enumerable: true,
  24038. configurable: true
  24039. });
  24040. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24041. /** The default material used on meshes when no material is affected */
  24042. get: function () {
  24043. if (!this._defaultMaterial) {
  24044. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24045. }
  24046. return this._defaultMaterial;
  24047. },
  24048. /** The default material used on meshes when no material is affected */
  24049. set: function (value) {
  24050. this._defaultMaterial = value;
  24051. },
  24052. enumerable: true,
  24053. configurable: true
  24054. });
  24055. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24056. get: function () {
  24057. return this._texturesEnabled;
  24058. },
  24059. /**
  24060. * Gets or sets a boolean indicating if textures are enabled on this scene
  24061. */
  24062. set: function (value) {
  24063. if (this._texturesEnabled === value) {
  24064. return;
  24065. }
  24066. this._texturesEnabled = value;
  24067. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24073. get: function () {
  24074. return this._skeletonsEnabled;
  24075. },
  24076. /**
  24077. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24078. */
  24079. set: function (value) {
  24080. if (this._skeletonsEnabled === value) {
  24081. return;
  24082. }
  24083. this._skeletonsEnabled = value;
  24084. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24085. },
  24086. enumerable: true,
  24087. configurable: true
  24088. });
  24089. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24090. /**
  24091. * Gets the postprocess render pipeline manager
  24092. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24093. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24094. */
  24095. get: function () {
  24096. if (!this._postProcessRenderPipelineManager) {
  24097. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24098. }
  24099. return this._postProcessRenderPipelineManager;
  24100. },
  24101. enumerable: true,
  24102. configurable: true
  24103. });
  24104. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24105. /**
  24106. * Gets the main soundtrack associated with the scene
  24107. */
  24108. get: function () {
  24109. if (!this._mainSoundTrack) {
  24110. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24111. }
  24112. return this._mainSoundTrack;
  24113. },
  24114. enumerable: true,
  24115. configurable: true
  24116. });
  24117. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24118. /** @ignore */
  24119. get: function () {
  24120. return this._alternateRendering;
  24121. },
  24122. enumerable: true,
  24123. configurable: true
  24124. });
  24125. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24126. /**
  24127. * Gets the list of frustum planes (built from the active camera)
  24128. */
  24129. get: function () {
  24130. return this._frustumPlanes;
  24131. },
  24132. enumerable: true,
  24133. configurable: true
  24134. });
  24135. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24136. /**
  24137. * Gets the current geometry buffer associated to the scene.
  24138. */
  24139. get: function () {
  24140. return this._geometryBufferRenderer;
  24141. },
  24142. /**
  24143. * Sets the current geometry buffer for the scene.
  24144. */
  24145. set: function (geometryBufferRenderer) {
  24146. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24147. this._geometryBufferRenderer = geometryBufferRenderer;
  24148. }
  24149. },
  24150. enumerable: true,
  24151. configurable: true
  24152. });
  24153. Object.defineProperty(Scene.prototype, "debugLayer", {
  24154. /**
  24155. * Gets the debug layer associated with the scene
  24156. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24157. */
  24158. get: function () {
  24159. if (!this._debugLayer) {
  24160. this._debugLayer = new BABYLON.DebugLayer(this);
  24161. }
  24162. return this._debugLayer;
  24163. },
  24164. enumerable: true,
  24165. configurable: true
  24166. });
  24167. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24168. /**
  24169. * Gets a boolean indicating if collisions are processed on a web worker
  24170. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24171. */
  24172. get: function () {
  24173. return this._workerCollisions;
  24174. },
  24175. set: function (enabled) {
  24176. if (!BABYLON.CollisionCoordinatorLegacy) {
  24177. return;
  24178. }
  24179. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24180. this._workerCollisions = enabled;
  24181. if (this.collisionCoordinator) {
  24182. this.collisionCoordinator.destroy();
  24183. }
  24184. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24185. this.collisionCoordinator.init(this);
  24186. },
  24187. enumerable: true,
  24188. configurable: true
  24189. });
  24190. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24191. /**
  24192. * Gets the octree used to boost mesh selection (picking)
  24193. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24194. */
  24195. get: function () {
  24196. return this._selectionOctree;
  24197. },
  24198. enumerable: true,
  24199. configurable: true
  24200. });
  24201. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24202. /**
  24203. * Gets the mesh that is currently under the pointer
  24204. */
  24205. get: function () {
  24206. return this._pointerOverMesh;
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Scene.prototype, "pointerX", {
  24212. /**
  24213. * Gets the current on-screen X position of the pointer
  24214. */
  24215. get: function () {
  24216. return this._pointerX;
  24217. },
  24218. enumerable: true,
  24219. configurable: true
  24220. });
  24221. Object.defineProperty(Scene.prototype, "pointerY", {
  24222. /**
  24223. * Gets the current on-screen Y position of the pointer
  24224. */
  24225. get: function () {
  24226. return this._pointerY;
  24227. },
  24228. enumerable: true,
  24229. configurable: true
  24230. });
  24231. /**
  24232. * Gets the cached material (ie. the latest rendered one)
  24233. * @returns the cached material
  24234. */
  24235. Scene.prototype.getCachedMaterial = function () {
  24236. return this._cachedMaterial;
  24237. };
  24238. /**
  24239. * Gets the cached effect (ie. the latest rendered one)
  24240. * @returns the cached effect
  24241. */
  24242. Scene.prototype.getCachedEffect = function () {
  24243. return this._cachedEffect;
  24244. };
  24245. /**
  24246. * Gets the cached visibility state (ie. the latest rendered one)
  24247. * @returns the cached visibility state
  24248. */
  24249. Scene.prototype.getCachedVisibility = function () {
  24250. return this._cachedVisibility;
  24251. };
  24252. /**
  24253. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24254. * @param material defines the current material
  24255. * @param effect defines the current effect
  24256. * @param visibility defines the current visibility state
  24257. * @returns true if one parameter is not cached
  24258. */
  24259. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24260. if (visibility === void 0) { visibility = 1; }
  24261. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24262. };
  24263. /**
  24264. * Gets the bounding box renderer associated with the scene
  24265. * @returns a BoundingBoxRenderer
  24266. */
  24267. Scene.prototype.getBoundingBoxRenderer = function () {
  24268. if (!this._boundingBoxRenderer) {
  24269. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24270. }
  24271. return this._boundingBoxRenderer;
  24272. };
  24273. /**
  24274. * Gets the outline renderer associated with the scene
  24275. * @returns a OutlineRenderer
  24276. */
  24277. Scene.prototype.getOutlineRenderer = function () {
  24278. return this._outlineRenderer;
  24279. };
  24280. /**
  24281. * Gets the engine associated with the scene
  24282. * @returns an Engine
  24283. */
  24284. Scene.prototype.getEngine = function () {
  24285. return this._engine;
  24286. };
  24287. /**
  24288. * Gets the total number of vertices rendered per frame
  24289. * @returns the total number of vertices rendered per frame
  24290. */
  24291. Scene.prototype.getTotalVertices = function () {
  24292. return this._totalVertices.current;
  24293. };
  24294. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24295. /**
  24296. * Gets the performance counter for total vertices
  24297. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24298. */
  24299. get: function () {
  24300. return this._totalVertices;
  24301. },
  24302. enumerable: true,
  24303. configurable: true
  24304. });
  24305. /**
  24306. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24307. * @returns the total number of active indices rendered per frame
  24308. */
  24309. Scene.prototype.getActiveIndices = function () {
  24310. return this._activeIndices.current;
  24311. };
  24312. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24313. /**
  24314. * Gets the performance counter for active indices
  24315. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24316. */
  24317. get: function () {
  24318. return this._activeIndices;
  24319. },
  24320. enumerable: true,
  24321. configurable: true
  24322. });
  24323. /**
  24324. * Gets the total number of active particles rendered per frame
  24325. * @returns the total number of active particles rendered per frame
  24326. */
  24327. Scene.prototype.getActiveParticles = function () {
  24328. return this._activeParticles.current;
  24329. };
  24330. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24331. /**
  24332. * Gets the performance counter for active particles
  24333. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24334. */
  24335. get: function () {
  24336. return this._activeParticles;
  24337. },
  24338. enumerable: true,
  24339. configurable: true
  24340. });
  24341. /**
  24342. * Gets the total number of active bones rendered per frame
  24343. * @returns the total number of active bones rendered per frame
  24344. */
  24345. Scene.prototype.getActiveBones = function () {
  24346. return this._activeBones.current;
  24347. };
  24348. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24349. /**
  24350. * Gets the performance counter for active bones
  24351. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24352. */
  24353. get: function () {
  24354. return this._activeBones;
  24355. },
  24356. enumerable: true,
  24357. configurable: true
  24358. });
  24359. /** @ignore */
  24360. Scene.prototype.getInterFramePerfCounter = function () {
  24361. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24362. return 0;
  24363. };
  24364. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24365. /** @ignore */
  24366. get: function () {
  24367. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24368. return null;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. /** @ignore */
  24374. Scene.prototype.getLastFrameDuration = function () {
  24375. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24376. return 0;
  24377. };
  24378. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24379. /** @ignore */
  24380. get: function () {
  24381. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24382. return null;
  24383. },
  24384. enumerable: true,
  24385. configurable: true
  24386. });
  24387. /** @ignore */
  24388. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24389. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24390. return 0;
  24391. };
  24392. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24393. /** @ignore */
  24394. get: function () {
  24395. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24396. return null;
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. /**
  24402. * Gets the array of active meshes
  24403. * @returns an array of AbstractMesh
  24404. */
  24405. Scene.prototype.getActiveMeshes = function () {
  24406. return this._activeMeshes;
  24407. };
  24408. /** @ignore */
  24409. Scene.prototype.getRenderTargetsDuration = function () {
  24410. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24411. return 0;
  24412. };
  24413. /** @ignore */
  24414. Scene.prototype.getRenderDuration = function () {
  24415. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24416. return 0;
  24417. };
  24418. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24419. /** @ignore */
  24420. get: function () {
  24421. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24422. return null;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. /** @ignore */
  24428. Scene.prototype.getParticlesDuration = function () {
  24429. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24430. return 0;
  24431. };
  24432. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24433. /** @ignore */
  24434. get: function () {
  24435. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24436. return null;
  24437. },
  24438. enumerable: true,
  24439. configurable: true
  24440. });
  24441. /** @ignore */
  24442. Scene.prototype.getSpritesDuration = function () {
  24443. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24444. return 0;
  24445. };
  24446. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24447. /** @ignore */
  24448. get: function () {
  24449. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24450. return null;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. /**
  24456. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24457. * @returns a number
  24458. */
  24459. Scene.prototype.getAnimationRatio = function () {
  24460. return this._animationRatio;
  24461. };
  24462. /**
  24463. * Gets an unique Id for the current frame
  24464. * @returns a number
  24465. */
  24466. Scene.prototype.getRenderId = function () {
  24467. return this._renderId;
  24468. };
  24469. /** Call this function if you want to manually increment the render Id*/
  24470. Scene.prototype.incrementRenderId = function () {
  24471. this._renderId++;
  24472. };
  24473. Scene.prototype._updatePointerPosition = function (evt) {
  24474. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24475. if (!canvasRect) {
  24476. return;
  24477. }
  24478. this._pointerX = evt.clientX - canvasRect.left;
  24479. this._pointerY = evt.clientY - canvasRect.top;
  24480. this._unTranslatedPointerX = this._pointerX;
  24481. this._unTranslatedPointerY = this._pointerY;
  24482. };
  24483. Scene.prototype._createUbo = function () {
  24484. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24485. this._sceneUbo.addUniform("viewProjection", 16);
  24486. this._sceneUbo.addUniform("view", 16);
  24487. };
  24488. Scene.prototype._createAlternateUbo = function () {
  24489. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24490. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24491. this._alternateSceneUbo.addUniform("view", 16);
  24492. };
  24493. // Pointers handling
  24494. /**
  24495. * Use this method to simulate a pointer move on a mesh
  24496. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24497. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24498. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24499. * @returns the current scene
  24500. */
  24501. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24502. var evt = new PointerEvent("pointermove", pointerEventInit);
  24503. return this._processPointerMove(pickResult, evt);
  24504. };
  24505. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24506. var canvas = this._engine.getRenderingCanvas();
  24507. if (!canvas) {
  24508. return this;
  24509. }
  24510. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24511. this.setPointerOverSprite(null);
  24512. this.setPointerOverMesh(pickResult.pickedMesh);
  24513. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24514. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24515. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24516. }
  24517. else {
  24518. canvas.style.cursor = this.hoverCursor;
  24519. }
  24520. }
  24521. else {
  24522. canvas.style.cursor = this.defaultCursor;
  24523. }
  24524. }
  24525. else {
  24526. this.setPointerOverMesh(null);
  24527. // Sprites
  24528. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24529. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24530. this.setPointerOverSprite(pickResult.pickedSprite);
  24531. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24532. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24533. }
  24534. else {
  24535. canvas.style.cursor = this.hoverCursor;
  24536. }
  24537. }
  24538. else {
  24539. this.setPointerOverSprite(null);
  24540. // Restore pointer
  24541. canvas.style.cursor = this.defaultCursor;
  24542. }
  24543. }
  24544. if (pickResult) {
  24545. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24546. if (this.onPointerMove) {
  24547. this.onPointerMove(evt, pickResult, type);
  24548. }
  24549. if (this.onPointerObservable.hasObservers()) {
  24550. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24551. this.onPointerObservable.notifyObservers(pi, type);
  24552. }
  24553. }
  24554. return this;
  24555. };
  24556. /**
  24557. * Use this method to simulate a pointer down on a mesh
  24558. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24559. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24560. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24561. * @returns the current scene
  24562. */
  24563. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24564. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24565. return this._processPointerDown(pickResult, evt);
  24566. };
  24567. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24568. var _this = this;
  24569. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24570. this._pickedDownMesh = pickResult.pickedMesh;
  24571. var actionManager = pickResult.pickedMesh.actionManager;
  24572. if (actionManager) {
  24573. if (actionManager.hasPickTriggers) {
  24574. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24575. switch (evt.button) {
  24576. case 0:
  24577. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24578. break;
  24579. case 1:
  24580. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24581. break;
  24582. case 2:
  24583. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24584. break;
  24585. }
  24586. }
  24587. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24588. window.setTimeout(function () {
  24589. 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);
  24590. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24591. if (_this._totalPointersPressed !== 0 &&
  24592. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24593. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24594. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24595. _this._startingPointerTime = 0;
  24596. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24597. }
  24598. }
  24599. }, Scene.LongPressDelay);
  24600. }
  24601. }
  24602. }
  24603. if (pickResult) {
  24604. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24605. if (this.onPointerDown) {
  24606. this.onPointerDown(evt, pickResult, type);
  24607. }
  24608. if (this.onPointerObservable.hasObservers()) {
  24609. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24610. this.onPointerObservable.notifyObservers(pi, type);
  24611. }
  24612. }
  24613. return this;
  24614. };
  24615. /**
  24616. * Use this method to simulate a pointer up on a mesh
  24617. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24618. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24619. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24620. * @returns the current scene
  24621. */
  24622. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24623. var evt = new PointerEvent("pointerup", pointerEventInit);
  24624. var clickInfo = new ClickInfo();
  24625. clickInfo.singleClick = true;
  24626. clickInfo.ignore = true;
  24627. return this._processPointerUp(pickResult, evt, clickInfo);
  24628. };
  24629. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24630. if (pickResult && pickResult && pickResult.pickedMesh) {
  24631. this._pickedUpMesh = pickResult.pickedMesh;
  24632. if (this._pickedDownMesh === this._pickedUpMesh) {
  24633. if (this.onPointerPick) {
  24634. this.onPointerPick(evt, pickResult);
  24635. }
  24636. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24637. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24638. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24639. this.onPointerObservable.notifyObservers(pi, type_1);
  24640. }
  24641. }
  24642. if (pickResult.pickedMesh.actionManager) {
  24643. if (clickInfo.ignore) {
  24644. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24645. }
  24646. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24647. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24648. }
  24649. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24650. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24651. }
  24652. }
  24653. }
  24654. if (this._pickedDownMesh &&
  24655. this._pickedDownMesh.actionManager &&
  24656. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24657. this._pickedDownMesh !== this._pickedUpMesh) {
  24658. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24659. }
  24660. var type = BABYLON.PointerEventTypes.POINTERUP;
  24661. if (this.onPointerObservable.hasObservers()) {
  24662. if (!clickInfo.ignore) {
  24663. if (!clickInfo.hasSwiped) {
  24664. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24665. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24666. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24667. this.onPointerObservable.notifyObservers(pi, type_2);
  24668. }
  24669. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24670. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24671. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24672. this.onPointerObservable.notifyObservers(pi, type_3);
  24673. }
  24674. }
  24675. }
  24676. else {
  24677. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24678. this.onPointerObservable.notifyObservers(pi, type);
  24679. }
  24680. }
  24681. if (this.onPointerUp) {
  24682. this.onPointerUp(evt, pickResult, type);
  24683. }
  24684. return this;
  24685. };
  24686. /**
  24687. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24688. * @param attachUp defines if you want to attach events to pointerup
  24689. * @param attachDown defines if you want to attach events to pointerdown
  24690. * @param attachMove defines if you want to attach events to pointermove
  24691. */
  24692. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24693. var _this = this;
  24694. if (attachUp === void 0) { attachUp = true; }
  24695. if (attachDown === void 0) { attachDown = true; }
  24696. if (attachMove === void 0) { attachMove = true; }
  24697. this._initActionManager = function (act, clickInfo) {
  24698. if (!_this._meshPickProceed) {
  24699. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24700. _this._currentPickResult = pickResult;
  24701. if (pickResult) {
  24702. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24703. }
  24704. _this._meshPickProceed = true;
  24705. }
  24706. return act;
  24707. };
  24708. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24709. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24710. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24711. btn !== _this._previousButtonPressed) {
  24712. _this._doubleClickOccured = false;
  24713. clickInfo.singleClick = true;
  24714. clickInfo.ignore = false;
  24715. cb(clickInfo, _this._currentPickResult);
  24716. }
  24717. };
  24718. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24719. var clickInfo = new ClickInfo();
  24720. _this._currentPickResult = null;
  24721. var act = null;
  24722. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24723. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24724. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24725. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24726. act = _this._initActionManager(act, clickInfo);
  24727. if (act)
  24728. checkPicking = act.hasPickTriggers;
  24729. }
  24730. if (checkPicking) {
  24731. var btn = evt.button;
  24732. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24733. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24734. if (!clickInfo.hasSwiped) {
  24735. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24736. if (!checkSingleClickImmediately) {
  24737. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24738. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24739. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24740. act = _this._initActionManager(act, clickInfo);
  24741. if (act)
  24742. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24743. }
  24744. }
  24745. if (checkSingleClickImmediately) {
  24746. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24747. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24748. btn !== _this._previousButtonPressed) {
  24749. clickInfo.singleClick = true;
  24750. cb(clickInfo, _this._currentPickResult);
  24751. }
  24752. }
  24753. // at least one double click is required to be check and exclusive double click is enabled
  24754. else {
  24755. // wait that no double click has been raised during the double click delay
  24756. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24757. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24758. }
  24759. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24760. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24761. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24762. act = _this._initActionManager(act, clickInfo);
  24763. if (act)
  24764. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24765. }
  24766. if (checkDoubleClick) {
  24767. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24768. if (btn === _this._previousButtonPressed &&
  24769. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24770. !_this._doubleClickOccured) {
  24771. // pointer has not moved for 2 clicks, it's a double click
  24772. if (!clickInfo.hasSwiped &&
  24773. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24774. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24775. _this._previousStartingPointerTime = 0;
  24776. _this._doubleClickOccured = true;
  24777. clickInfo.doubleClick = true;
  24778. clickInfo.ignore = false;
  24779. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24780. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24781. }
  24782. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24783. cb(clickInfo, _this._currentPickResult);
  24784. }
  24785. // if the two successive clicks are too far, it's just two simple clicks
  24786. else {
  24787. _this._doubleClickOccured = false;
  24788. _this._previousStartingPointerTime = _this._startingPointerTime;
  24789. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24790. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24791. _this._previousButtonPressed = btn;
  24792. if (Scene.ExclusiveDoubleClickMode) {
  24793. if (_this._previousDelayedSimpleClickTimeout) {
  24794. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24795. }
  24796. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24797. cb(clickInfo, _this._previousPickResult);
  24798. }
  24799. else {
  24800. cb(clickInfo, _this._currentPickResult);
  24801. }
  24802. }
  24803. }
  24804. // just the first click of the double has been raised
  24805. else {
  24806. _this._doubleClickOccured = false;
  24807. _this._previousStartingPointerTime = _this._startingPointerTime;
  24808. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24809. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24810. _this._previousButtonPressed = btn;
  24811. }
  24812. }
  24813. }
  24814. }
  24815. clickInfo.ignore = true;
  24816. cb(clickInfo, _this._currentPickResult);
  24817. };
  24818. this._spritePredicate = function (sprite) {
  24819. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24820. };
  24821. this._onPointerMove = function (evt) {
  24822. _this._updatePointerPosition(evt);
  24823. // PreObservable support
  24824. if (_this.onPrePointerObservable.hasObservers()) {
  24825. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24826. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24827. _this.onPrePointerObservable.notifyObservers(pi, type);
  24828. if (pi.skipOnPointerObservable) {
  24829. return;
  24830. }
  24831. }
  24832. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24833. return;
  24834. }
  24835. if (!_this.pointerMovePredicate) {
  24836. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24837. }
  24838. // Meshes
  24839. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24840. _this._processPointerMove(pickResult, evt);
  24841. };
  24842. this._onPointerDown = function (evt) {
  24843. _this._totalPointersPressed++;
  24844. _this._pickedDownMesh = null;
  24845. _this._meshPickProceed = false;
  24846. _this._updatePointerPosition(evt);
  24847. if (_this.preventDefaultOnPointerDown && canvas) {
  24848. evt.preventDefault();
  24849. canvas.focus();
  24850. }
  24851. // PreObservable support
  24852. if (_this.onPrePointerObservable.hasObservers()) {
  24853. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24854. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24855. _this.onPrePointerObservable.notifyObservers(pi, type);
  24856. if (pi.skipOnPointerObservable) {
  24857. return;
  24858. }
  24859. }
  24860. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24861. return;
  24862. }
  24863. _this._startingPointerPosition.x = _this._pointerX;
  24864. _this._startingPointerPosition.y = _this._pointerY;
  24865. _this._startingPointerTime = Date.now();
  24866. if (!_this.pointerDownPredicate) {
  24867. _this.pointerDownPredicate = function (mesh) {
  24868. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24869. };
  24870. }
  24871. // Meshes
  24872. _this._pickedDownMesh = null;
  24873. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24874. _this._processPointerDown(pickResult, evt);
  24875. // Sprites
  24876. _this._pickedDownSprite = null;
  24877. if (_this.spriteManagers.length > 0) {
  24878. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24879. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24880. if (pickResult.pickedSprite.actionManager) {
  24881. _this._pickedDownSprite = pickResult.pickedSprite;
  24882. switch (evt.button) {
  24883. case 0:
  24884. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24885. break;
  24886. case 1:
  24887. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24888. break;
  24889. case 2:
  24890. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24891. break;
  24892. }
  24893. if (pickResult.pickedSprite.actionManager) {
  24894. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  24895. }
  24896. }
  24897. }
  24898. }
  24899. };
  24900. this._onPointerUp = function (evt) {
  24901. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  24902. return; // So we need to test it the pointer down was pressed before.
  24903. }
  24904. _this._totalPointersPressed--;
  24905. _this._pickedUpMesh = null;
  24906. _this._meshPickProceed = false;
  24907. _this._updatePointerPosition(evt);
  24908. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  24909. // PreObservable support
  24910. if (_this.onPrePointerObservable.hasObservers()) {
  24911. if (!clickInfo.ignore) {
  24912. if (!clickInfo.hasSwiped) {
  24913. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24914. var type = BABYLON.PointerEventTypes.POINTERTAP;
  24915. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24916. _this.onPrePointerObservable.notifyObservers(pi, type);
  24917. if (pi.skipOnPointerObservable) {
  24918. return;
  24919. }
  24920. }
  24921. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24922. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24923. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24924. _this.onPrePointerObservable.notifyObservers(pi, type);
  24925. if (pi.skipOnPointerObservable) {
  24926. return;
  24927. }
  24928. }
  24929. }
  24930. }
  24931. else {
  24932. var type = BABYLON.PointerEventTypes.POINTERUP;
  24933. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24934. _this.onPrePointerObservable.notifyObservers(pi, type);
  24935. if (pi.skipOnPointerObservable) {
  24936. return;
  24937. }
  24938. }
  24939. }
  24940. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24941. return;
  24942. }
  24943. if (!_this.pointerUpPredicate) {
  24944. _this.pointerUpPredicate = function (mesh) {
  24945. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24946. };
  24947. }
  24948. // Meshes
  24949. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  24950. _this._initActionManager(null, clickInfo);
  24951. }
  24952. if (!pickResult) {
  24953. pickResult = _this._currentPickResult;
  24954. }
  24955. _this._processPointerUp(pickResult, evt, clickInfo);
  24956. // Sprites
  24957. if (_this.spriteManagers.length > 0) {
  24958. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  24959. if (spritePickResult) {
  24960. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  24961. if (spritePickResult.pickedSprite.actionManager) {
  24962. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24963. if (spritePickResult.pickedSprite.actionManager) {
  24964. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  24965. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  24966. }
  24967. }
  24968. }
  24969. }
  24970. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  24971. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  24972. }
  24973. }
  24974. }
  24975. _this._previousPickResult = _this._currentPickResult;
  24976. });
  24977. };
  24978. this._onKeyDown = function (evt) {
  24979. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  24980. if (_this.onPreKeyboardObservable.hasObservers()) {
  24981. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24982. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  24983. if (pi.skipOnPointerObservable) {
  24984. return;
  24985. }
  24986. }
  24987. if (_this.onKeyboardObservable.hasObservers()) {
  24988. var pi = new BABYLON.KeyboardInfo(type, evt);
  24989. _this.onKeyboardObservable.notifyObservers(pi, type);
  24990. }
  24991. if (_this.actionManager) {
  24992. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  24993. }
  24994. };
  24995. this._onKeyUp = function (evt) {
  24996. var type = BABYLON.KeyboardEventTypes.KEYUP;
  24997. if (_this.onPreKeyboardObservable.hasObservers()) {
  24998. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  24999. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25000. if (pi.skipOnPointerObservable) {
  25001. return;
  25002. }
  25003. }
  25004. if (_this.onKeyboardObservable.hasObservers()) {
  25005. var pi = new BABYLON.KeyboardInfo(type, evt);
  25006. _this.onKeyboardObservable.notifyObservers(pi, type);
  25007. }
  25008. if (_this.actionManager) {
  25009. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25010. }
  25011. };
  25012. var engine = this.getEngine();
  25013. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25014. if (!canvas) {
  25015. return;
  25016. }
  25017. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25018. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25019. });
  25020. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25021. if (!canvas) {
  25022. return;
  25023. }
  25024. canvas.removeEventListener("keydown", _this._onKeyDown);
  25025. canvas.removeEventListener("keyup", _this._onKeyUp);
  25026. });
  25027. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25028. var canvas = this._engine.getRenderingCanvas();
  25029. if (!canvas) {
  25030. return;
  25031. }
  25032. if (attachMove) {
  25033. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25034. // Wheel
  25035. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25036. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25037. }
  25038. if (attachDown) {
  25039. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25040. }
  25041. if (attachUp) {
  25042. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25043. }
  25044. canvas.tabIndex = 1;
  25045. };
  25046. /** Detaches all event handlers*/
  25047. Scene.prototype.detachControl = function () {
  25048. var engine = this.getEngine();
  25049. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25050. var canvas = engine.getRenderingCanvas();
  25051. if (!canvas) {
  25052. return;
  25053. }
  25054. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25055. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25056. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25057. if (this._onCanvasBlurObserver) {
  25058. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25059. }
  25060. if (this._onCanvasFocusObserver) {
  25061. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25062. }
  25063. // Wheel
  25064. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25065. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25066. // Keyboard
  25067. canvas.removeEventListener("keydown", this._onKeyDown);
  25068. canvas.removeEventListener("keyup", this._onKeyUp);
  25069. // Observables
  25070. this.onKeyboardObservable.clear();
  25071. this.onPreKeyboardObservable.clear();
  25072. this.onPointerObservable.clear();
  25073. this.onPrePointerObservable.clear();
  25074. };
  25075. /**
  25076. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25077. * Delay loaded resources are not taking in account
  25078. * @return true if all required resources are ready
  25079. */
  25080. Scene.prototype.isReady = function () {
  25081. if (this._isDisposed) {
  25082. return false;
  25083. }
  25084. if (this._pendingData.length > 0) {
  25085. return false;
  25086. }
  25087. var index;
  25088. var engine = this.getEngine();
  25089. // Geometries
  25090. for (index = 0; index < this._geometries.length; index++) {
  25091. var geometry = this._geometries[index];
  25092. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25093. return false;
  25094. }
  25095. }
  25096. // Meshes
  25097. for (index = 0; index < this.meshes.length; index++) {
  25098. var mesh = this.meshes[index];
  25099. if (!mesh.isEnabled()) {
  25100. continue;
  25101. }
  25102. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25103. continue;
  25104. }
  25105. if (!mesh.isReady(true)) {
  25106. return false;
  25107. }
  25108. // Effect layers
  25109. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25110. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25111. var layer = _a[_i];
  25112. if (!layer.hasMesh(mesh)) {
  25113. continue;
  25114. }
  25115. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25116. var subMesh = _c[_b];
  25117. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25118. return false;
  25119. }
  25120. }
  25121. }
  25122. }
  25123. // Post-processes
  25124. if (this.activeCameras && this.activeCameras.length > 0) {
  25125. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25126. var camera = _e[_d];
  25127. if (!camera.isReady(true)) {
  25128. return false;
  25129. }
  25130. }
  25131. }
  25132. else if (this.activeCamera) {
  25133. if (!this.activeCamera.isReady(true)) {
  25134. return false;
  25135. }
  25136. }
  25137. // Particles
  25138. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25139. var particleSystem = _g[_f];
  25140. if (!particleSystem.isReady()) {
  25141. return false;
  25142. }
  25143. }
  25144. return true;
  25145. };
  25146. /** Resets all cached information relative to material (including effect and visibility) */
  25147. Scene.prototype.resetCachedMaterial = function () {
  25148. this._cachedMaterial = null;
  25149. this._cachedEffect = null;
  25150. this._cachedVisibility = null;
  25151. };
  25152. /**
  25153. * Registers a function to be called before every frame render
  25154. * @param func defines the function to register
  25155. */
  25156. Scene.prototype.registerBeforeRender = function (func) {
  25157. this.onBeforeRenderObservable.add(func);
  25158. };
  25159. /**
  25160. * Unregisters a function called before every frame render
  25161. * @param func defines the function to unregister
  25162. */
  25163. Scene.prototype.unregisterBeforeRender = function (func) {
  25164. this.onBeforeRenderObservable.removeCallback(func);
  25165. };
  25166. /**
  25167. * Registers a function to be called after every frame render
  25168. * @param func defines the function to register
  25169. */
  25170. Scene.prototype.registerAfterRender = function (func) {
  25171. this.onAfterRenderObservable.add(func);
  25172. };
  25173. /**
  25174. * Unregisters a function called after every frame render
  25175. * @param func defines the function to unregister
  25176. */
  25177. Scene.prototype.unregisterAfterRender = function (func) {
  25178. this.onAfterRenderObservable.removeCallback(func);
  25179. };
  25180. Scene.prototype._executeOnceBeforeRender = function (func) {
  25181. var _this = this;
  25182. var execFunc = function () {
  25183. func();
  25184. setTimeout(function () {
  25185. _this.unregisterBeforeRender(execFunc);
  25186. });
  25187. };
  25188. this.registerBeforeRender(execFunc);
  25189. };
  25190. /**
  25191. * The provided function will run before render once and will be disposed afterwards.
  25192. * A timeout delay can be provided so that the function will be executed in N ms.
  25193. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25194. * @param func The function to be executed.
  25195. * @param timeout optional delay in ms
  25196. */
  25197. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25198. var _this = this;
  25199. if (timeout !== undefined) {
  25200. setTimeout(function () {
  25201. _this._executeOnceBeforeRender(func);
  25202. }, timeout);
  25203. }
  25204. else {
  25205. this._executeOnceBeforeRender(func);
  25206. }
  25207. };
  25208. /** @ignore */
  25209. Scene.prototype._addPendingData = function (data) {
  25210. this._pendingData.push(data);
  25211. };
  25212. /** @ignore */
  25213. Scene.prototype._removePendingData = function (data) {
  25214. var wasLoading = this.isLoading;
  25215. var index = this._pendingData.indexOf(data);
  25216. if (index !== -1) {
  25217. this._pendingData.splice(index, 1);
  25218. }
  25219. if (wasLoading && !this.isLoading) {
  25220. this.onDataLoadedObservable.notifyObservers(this);
  25221. }
  25222. };
  25223. /**
  25224. * Returns the number of items waiting to be loaded
  25225. * @returns the number of items waiting to be loaded
  25226. */
  25227. Scene.prototype.getWaitingItemsCount = function () {
  25228. return this._pendingData.length;
  25229. };
  25230. Object.defineProperty(Scene.prototype, "isLoading", {
  25231. /**
  25232. * Returns a boolean indicating if the scene is still loading data
  25233. */
  25234. get: function () {
  25235. return this._pendingData.length > 0;
  25236. },
  25237. enumerable: true,
  25238. configurable: true
  25239. });
  25240. /**
  25241. * Registers a function to be executed when the scene is ready
  25242. * @param {Function} func - the function to be executed
  25243. */
  25244. Scene.prototype.executeWhenReady = function (func) {
  25245. var _this = this;
  25246. this.onReadyObservable.add(func);
  25247. if (this._executeWhenReadyTimeoutId !== -1) {
  25248. return;
  25249. }
  25250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25251. _this._checkIsReady();
  25252. }, 150);
  25253. };
  25254. /**
  25255. * Returns a promise that resolves when the scene is ready
  25256. * @returns A promise that resolves when the scene is ready
  25257. */
  25258. Scene.prototype.whenReadyAsync = function () {
  25259. var _this = this;
  25260. return new Promise(function (resolve) {
  25261. _this.executeWhenReady(function () {
  25262. resolve();
  25263. });
  25264. });
  25265. };
  25266. /** @ignore */
  25267. Scene.prototype._checkIsReady = function () {
  25268. var _this = this;
  25269. if (this.isReady()) {
  25270. this.onReadyObservable.notifyObservers(this);
  25271. this.onReadyObservable.clear();
  25272. this._executeWhenReadyTimeoutId = -1;
  25273. return;
  25274. }
  25275. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25276. _this._checkIsReady();
  25277. }, 150);
  25278. };
  25279. // Animations
  25280. /**
  25281. * Will start the animation sequence of a given target
  25282. * @param target defines the target
  25283. * @param from defines from which frame should animation start
  25284. * @param to defines until which frame should animation run.
  25285. * @param weight defines the weight to apply to the animation (1.0 by default)
  25286. * @param loop defines if the animation loops
  25287. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25288. * @param onAnimationEnd defines the function to be executed when the animation ends
  25289. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25290. * @returns the animatable object created for this animation
  25291. */
  25292. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25293. if (weight === void 0) { weight = 1.0; }
  25294. if (speedRatio === void 0) { speedRatio = 1.0; }
  25295. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25296. returnedAnimatable.weight = weight;
  25297. return returnedAnimatable;
  25298. };
  25299. /**
  25300. * Will start the animation sequence of a given target
  25301. * @param target defines the target
  25302. * @param from defines from which frame should animation start
  25303. * @param to defines until which frame should animation run.
  25304. * @param loop defines if the animation loops
  25305. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25306. * @param onAnimationEnd defines the function to be executed when the animation ends
  25307. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25308. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25309. * @returns the animatable object created for this animation
  25310. */
  25311. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25312. if (speedRatio === void 0) { speedRatio = 1.0; }
  25313. if (stopCurrent === void 0) { stopCurrent = true; }
  25314. if (from > to && speedRatio > 0) {
  25315. speedRatio *= -1;
  25316. }
  25317. if (stopCurrent) {
  25318. this.stopAnimation(target);
  25319. }
  25320. if (!animatable) {
  25321. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25322. }
  25323. // Local animations
  25324. if (target.animations) {
  25325. animatable.appendAnimations(target, target.animations);
  25326. }
  25327. // Children animations
  25328. if (target.getAnimatables) {
  25329. var animatables = target.getAnimatables();
  25330. for (var index = 0; index < animatables.length; index++) {
  25331. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25332. }
  25333. }
  25334. animatable.reset();
  25335. return animatable;
  25336. };
  25337. /**
  25338. * Begin a new animation on a given node
  25339. * @param target defines the target where the animation will take place
  25340. * @param animations defines the list of animations to start
  25341. * @param from defines the initial value
  25342. * @param to defines the final value
  25343. * @param loop defines if you want animation to loop (off by default)
  25344. * @param speedRatio defines the speed ratio to apply to all animations
  25345. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25346. * @returns the list of created animatables
  25347. */
  25348. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25349. if (speedRatio === undefined) {
  25350. speedRatio = 1.0;
  25351. }
  25352. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25353. return animatable;
  25354. };
  25355. /**
  25356. * Begin a new animation on a given node and its hierarchy
  25357. * @param target defines the root node where the animation will take place
  25358. * @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.
  25359. * @param animations defines the list of animations to start
  25360. * @param from defines the initial value
  25361. * @param to defines the final value
  25362. * @param loop defines if you want animation to loop (off by default)
  25363. * @param speedRatio defines the speed ratio to apply to all animations
  25364. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25365. * @returns the list of animatables created for all nodes
  25366. */
  25367. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25368. var children = target.getDescendants(directDescendantsOnly);
  25369. var result = [];
  25370. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25371. var child = children_1[_i];
  25372. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25373. }
  25374. return result;
  25375. };
  25376. /**
  25377. * Gets the animatable associated with a specific target
  25378. * @param target defines the target of the animatable
  25379. * @returns the required animatable if found
  25380. */
  25381. Scene.prototype.getAnimatableByTarget = function (target) {
  25382. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25383. if (this._activeAnimatables[index].target === target) {
  25384. return this._activeAnimatables[index];
  25385. }
  25386. }
  25387. return null;
  25388. };
  25389. /**
  25390. * Gets all animatables associated with a given target
  25391. * @param target defines the target to look animatables for
  25392. * @returns an array of Animatables
  25393. */
  25394. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25395. var result = [];
  25396. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25397. if (this._activeAnimatables[index].target === target) {
  25398. result.push(this._activeAnimatables[index]);
  25399. }
  25400. }
  25401. return result;
  25402. };
  25403. Object.defineProperty(Scene.prototype, "animatables", {
  25404. /**
  25405. * Gets all animatable attached to the scene
  25406. */
  25407. get: function () {
  25408. return this._activeAnimatables;
  25409. },
  25410. enumerable: true,
  25411. configurable: true
  25412. });
  25413. /**
  25414. * Will stop the animation of the given target
  25415. * @param target - the target
  25416. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25417. */
  25418. Scene.prototype.stopAnimation = function (target, animationName) {
  25419. var animatables = this.getAllAnimatablesByTarget(target);
  25420. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25421. var animatable = animatables_1[_i];
  25422. animatable.stop(animationName);
  25423. }
  25424. };
  25425. /**
  25426. * Stops and removes all animations that have been applied to the scene
  25427. */
  25428. Scene.prototype.stopAllAnimations = function () {
  25429. if (this._activeAnimatables) {
  25430. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25431. this._activeAnimatables[i].stop();
  25432. }
  25433. this._activeAnimatables = [];
  25434. }
  25435. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25436. var group = _a[_i];
  25437. group.stop();
  25438. }
  25439. };
  25440. Scene.prototype._animate = function () {
  25441. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25442. return;
  25443. }
  25444. // Getting time
  25445. var now = BABYLON.Tools.Now;
  25446. if (!this._animationTimeLast) {
  25447. if (this._pendingData.length > 0) {
  25448. return;
  25449. }
  25450. this._animationTimeLast = now;
  25451. }
  25452. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25453. this._animationTime += deltaTime;
  25454. this._animationTimeLast = now;
  25455. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25456. this._activeAnimatables[index]._animate(this._animationTime);
  25457. }
  25458. // Late animation bindings
  25459. this._processLateAnimationBindings();
  25460. };
  25461. /** @ignore */
  25462. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25463. var target = runtimeAnimation.target;
  25464. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25465. if (!target._lateAnimationHolders) {
  25466. target._lateAnimationHolders = {};
  25467. }
  25468. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25469. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25470. totalWeight: 0,
  25471. animations: []
  25472. };
  25473. }
  25474. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25475. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25476. };
  25477. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25478. var normalizer = 1.0;
  25479. var finalPosition = BABYLON.Tmp.Vector3[0];
  25480. var finalScaling = BABYLON.Tmp.Vector3[1];
  25481. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25482. var startIndex = 0;
  25483. var originalAnimation = holder.animations[0];
  25484. var scale = 1;
  25485. if (holder.totalWeight < 1.0) {
  25486. // We need to mix the original value in
  25487. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25488. scale = 1.0 - holder.totalWeight;
  25489. }
  25490. else {
  25491. startIndex = 1;
  25492. // We need to normalize the weights
  25493. normalizer = holder.totalWeight;
  25494. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25495. scale = originalAnimation.weight / normalizer;
  25496. if (scale == 1) {
  25497. return originalAnimation.currentValue;
  25498. }
  25499. }
  25500. finalScaling.scaleInPlace(scale);
  25501. finalPosition.scaleInPlace(scale);
  25502. finalQuaternion.scaleInPlace(scale);
  25503. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25504. var runtimeAnimation = holder.animations[animIndex];
  25505. var scale = runtimeAnimation.weight / normalizer;
  25506. var currentPosition = BABYLON.Tmp.Vector3[2];
  25507. var currentScaling = BABYLON.Tmp.Vector3[3];
  25508. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25509. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25510. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25511. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25512. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25513. }
  25514. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25515. return originalAnimation._workValue;
  25516. };
  25517. Scene.prototype._processLateAnimationBindings = function () {
  25518. if (!this._registeredForLateAnimationBindings.length) {
  25519. return;
  25520. }
  25521. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25522. var target = this._registeredForLateAnimationBindings.data[index];
  25523. for (var path in target._lateAnimationHolders) {
  25524. var holder = target._lateAnimationHolders[path];
  25525. var originalAnimation = holder.animations[0];
  25526. var originalValue = originalAnimation.originalValue;
  25527. var finalTarget = originalAnimation.target;
  25528. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25529. var finalValue = void 0;
  25530. if (matrixDecomposeMode) {
  25531. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25532. }
  25533. else {
  25534. var startIndex = 0;
  25535. var normalizer = 1.0;
  25536. if (holder.totalWeight < 1.0) {
  25537. // We need to mix the original value in
  25538. if (originalValue.scale) {
  25539. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25540. }
  25541. else {
  25542. finalValue = originalValue * (1.0 - holder.totalWeight);
  25543. }
  25544. }
  25545. else {
  25546. // We need to normalize the weights
  25547. normalizer = holder.totalWeight;
  25548. var scale_1 = originalAnimation.weight / normalizer;
  25549. if (scale_1 !== 1) {
  25550. if (originalAnimation.currentValue.scale) {
  25551. finalValue = originalAnimation.currentValue.scale(scale_1);
  25552. }
  25553. else {
  25554. finalValue = originalAnimation.currentValue * scale_1;
  25555. }
  25556. }
  25557. else {
  25558. finalValue = originalAnimation.currentValue;
  25559. }
  25560. startIndex = 1;
  25561. }
  25562. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25563. var runtimeAnimation = holder.animations[animIndex];
  25564. var scale = runtimeAnimation.weight / normalizer;
  25565. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25566. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25567. }
  25568. else {
  25569. finalValue += runtimeAnimation.currentValue * scale;
  25570. }
  25571. }
  25572. }
  25573. finalTarget[path] = finalValue;
  25574. }
  25575. target._lateAnimationHolders = {};
  25576. }
  25577. this._registeredForLateAnimationBindings.reset();
  25578. };
  25579. // Matrix
  25580. /** @ignore */
  25581. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25582. this._useAlternateCameraConfiguration = active;
  25583. };
  25584. /**
  25585. * Gets the current view matrix
  25586. * @returns a Matrix
  25587. */
  25588. Scene.prototype.getViewMatrix = function () {
  25589. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25590. };
  25591. /**
  25592. * Gets the current projection matrix
  25593. * @returns a Matrix
  25594. */
  25595. Scene.prototype.getProjectionMatrix = function () {
  25596. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25597. };
  25598. /**
  25599. * Gets the current transform matrix
  25600. * @returns a Matrix made of View * Projection
  25601. */
  25602. Scene.prototype.getTransformMatrix = function () {
  25603. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25604. };
  25605. /**
  25606. * Sets the current transform matrix
  25607. * @param view defines the View matrix to use
  25608. * @param projection defines the Projection matrix to use
  25609. */
  25610. Scene.prototype.setTransformMatrix = function (view, projection) {
  25611. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25612. return;
  25613. }
  25614. this._viewUpdateFlag = view.updateFlag;
  25615. this._projectionUpdateFlag = projection.updateFlag;
  25616. this._viewMatrix = view;
  25617. this._projectionMatrix = projection;
  25618. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25619. // Update frustum
  25620. if (!this._frustumPlanes) {
  25621. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25622. }
  25623. else {
  25624. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25625. }
  25626. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25627. var otherCamera = this.activeCamera._alternateCamera;
  25628. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25629. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25630. }
  25631. if (this._sceneUbo.useUbo) {
  25632. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25633. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25634. this._sceneUbo.update();
  25635. }
  25636. };
  25637. /** @ignore */
  25638. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25639. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25640. return;
  25641. }
  25642. this._alternateViewUpdateFlag = view.updateFlag;
  25643. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25644. this._alternateViewMatrix = view;
  25645. this._alternateProjectionMatrix = projection;
  25646. if (!this._alternateTransformMatrix) {
  25647. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25648. }
  25649. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25650. if (!this._alternateSceneUbo) {
  25651. this._createAlternateUbo();
  25652. }
  25653. if (this._alternateSceneUbo.useUbo) {
  25654. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25655. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25656. this._alternateSceneUbo.update();
  25657. }
  25658. };
  25659. /**
  25660. * Gets the uniform buffer used to store scene data
  25661. * @returns a UniformBuffer
  25662. */
  25663. Scene.prototype.getSceneUniformBuffer = function () {
  25664. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25665. };
  25666. /**
  25667. * Gets an unique (relatively to the current scene) Id
  25668. * @returns an unique number for the scene
  25669. */
  25670. Scene.prototype.getUniqueId = function () {
  25671. var result = Scene._uniqueIdCounter;
  25672. Scene._uniqueIdCounter++;
  25673. return result;
  25674. };
  25675. /**
  25676. * Add a mesh to the list of scene's meshes
  25677. * @param newMesh defines the mesh to add
  25678. */
  25679. Scene.prototype.addMesh = function (newMesh) {
  25680. this.meshes.push(newMesh);
  25681. //notify the collision coordinator
  25682. if (this.collisionCoordinator) {
  25683. this.collisionCoordinator.onMeshAdded(newMesh);
  25684. }
  25685. newMesh._resyncLightSources();
  25686. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25687. };
  25688. /**
  25689. * Remove a mesh for the list of scene's meshes
  25690. * @param toRemove defines the mesh to remove
  25691. * @returns the index where the mesh was in the mesh list
  25692. */
  25693. Scene.prototype.removeMesh = function (toRemove) {
  25694. var index = this.meshes.indexOf(toRemove);
  25695. if (index !== -1) {
  25696. // Remove from the scene if mesh found
  25697. this.meshes.splice(index, 1);
  25698. }
  25699. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25700. return index;
  25701. };
  25702. /**
  25703. * Add a transform node to the list of scene's transform nodes
  25704. * @param newTransformNode defines the transform node to add
  25705. */
  25706. Scene.prototype.addTransformNode = function (newTransformNode) {
  25707. this.transformNodes.push(newTransformNode);
  25708. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25709. };
  25710. /**
  25711. * Remove a transform node for the list of scene's transform nodes
  25712. * @param toRemove defines the transform node to remove
  25713. * @returns the index where the transform node was in the transform node list
  25714. */
  25715. Scene.prototype.removeTransformNode = function (toRemove) {
  25716. var index = this.transformNodes.indexOf(toRemove);
  25717. if (index !== -1) {
  25718. // Remove from the scene if found
  25719. this.transformNodes.splice(index, 1);
  25720. }
  25721. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25722. return index;
  25723. };
  25724. /**
  25725. * Remove a skeleton for the list of scene's skeletons
  25726. * @param toRemove defines the skeleton to remove
  25727. * @returns the index where the skeleton was in the skeleton list
  25728. */
  25729. Scene.prototype.removeSkeleton = function (toRemove) {
  25730. var index = this.skeletons.indexOf(toRemove);
  25731. if (index !== -1) {
  25732. // Remove from the scene if found
  25733. this.skeletons.splice(index, 1);
  25734. }
  25735. return index;
  25736. };
  25737. /**
  25738. * Remove a morph target for the list of scene's morph targets
  25739. * @param toRemove defines the morph target to remove
  25740. * @returns the index where the morph target was in the morph target list
  25741. */
  25742. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25743. var index = this.morphTargetManagers.indexOf(toRemove);
  25744. if (index !== -1) {
  25745. // Remove from the scene if found
  25746. this.morphTargetManagers.splice(index, 1);
  25747. }
  25748. return index;
  25749. };
  25750. /**
  25751. * Remove a light for the list of scene's lights
  25752. * @param toRemove defines the light to remove
  25753. * @returns the index where the light was in the light list
  25754. */
  25755. Scene.prototype.removeLight = function (toRemove) {
  25756. var index = this.lights.indexOf(toRemove);
  25757. if (index !== -1) {
  25758. // Remove from meshes
  25759. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25760. var mesh = _a[_i];
  25761. mesh._removeLightSource(toRemove);
  25762. }
  25763. // Remove from the scene if mesh found
  25764. this.lights.splice(index, 1);
  25765. this.sortLightsByPriority();
  25766. }
  25767. this.onLightRemovedObservable.notifyObservers(toRemove);
  25768. return index;
  25769. };
  25770. /**
  25771. * Remove a camera for the list of scene's cameras
  25772. * @param toRemove defines the camera to remove
  25773. * @returns the index where the camera was in the camera list
  25774. */
  25775. Scene.prototype.removeCamera = function (toRemove) {
  25776. var index = this.cameras.indexOf(toRemove);
  25777. if (index !== -1) {
  25778. // Remove from the scene if mesh found
  25779. this.cameras.splice(index, 1);
  25780. }
  25781. // Remove from activeCameras
  25782. var index2 = this.activeCameras.indexOf(toRemove);
  25783. if (index2 !== -1) {
  25784. // Remove from the scene if mesh found
  25785. this.activeCameras.splice(index2, 1);
  25786. }
  25787. // Reset the activeCamera
  25788. if (this.activeCamera === toRemove) {
  25789. if (this.cameras.length > 0) {
  25790. this.activeCamera = this.cameras[0];
  25791. }
  25792. else {
  25793. this.activeCamera = null;
  25794. }
  25795. }
  25796. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25797. return index;
  25798. };
  25799. /**
  25800. * Remove a particle system for the list of scene's particle systems
  25801. * @param toRemove defines the particle system to remove
  25802. * @returns the index where the particle system was in the particle system list
  25803. */
  25804. Scene.prototype.removeParticleSystem = function (toRemove) {
  25805. var index = this.particleSystems.indexOf(toRemove);
  25806. if (index !== -1) {
  25807. this.particleSystems.splice(index, 1);
  25808. }
  25809. return index;
  25810. };
  25811. /**
  25812. * Remove a animation for the list of scene's animations
  25813. * @param toRemove defines the animation to remove
  25814. * @returns the index where the animation was in the animation list
  25815. */
  25816. Scene.prototype.removeAnimation = function (toRemove) {
  25817. var index = this.animations.indexOf(toRemove);
  25818. if (index !== -1) {
  25819. this.animations.splice(index, 1);
  25820. }
  25821. return index;
  25822. };
  25823. /**
  25824. * Removes the given animation group from this scene.
  25825. * @param toRemove The animation group to remove
  25826. * @returns The index of the removed animation group
  25827. */
  25828. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25829. var index = this.animationGroups.indexOf(toRemove);
  25830. if (index !== -1) {
  25831. this.animationGroups.splice(index, 1);
  25832. }
  25833. return index;
  25834. };
  25835. /**
  25836. * Removes the given multi-material from this scene.
  25837. * @param toRemove The multi-material to remove
  25838. * @returns The index of the removed multi-material
  25839. */
  25840. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25841. var index = this.multiMaterials.indexOf(toRemove);
  25842. if (index !== -1) {
  25843. this.multiMaterials.splice(index, 1);
  25844. }
  25845. return index;
  25846. };
  25847. /**
  25848. * Removes the given material from this scene.
  25849. * @param toRemove The material to remove
  25850. * @returns The index of the removed material
  25851. */
  25852. Scene.prototype.removeMaterial = function (toRemove) {
  25853. var index = this.materials.indexOf(toRemove);
  25854. if (index !== -1) {
  25855. this.materials.splice(index, 1);
  25856. }
  25857. return index;
  25858. };
  25859. /**
  25860. * Removes the given lens flare system from this scene.
  25861. * @param toRemove The lens flare system to remove
  25862. * @returns The index of the removed lens flare system
  25863. */
  25864. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25865. var index = this.lensFlareSystems.indexOf(toRemove);
  25866. if (index !== -1) {
  25867. this.lensFlareSystems.splice(index, 1);
  25868. }
  25869. return index;
  25870. };
  25871. /**
  25872. * Removes the given action manager from this scene.
  25873. * @param toRemove The action manager to remove
  25874. * @returns The index of the removed action manager
  25875. */
  25876. Scene.prototype.removeActionManager = function (toRemove) {
  25877. var index = this._actionManagers.indexOf(toRemove);
  25878. if (index !== -1) {
  25879. this._actionManagers.splice(index, 1);
  25880. }
  25881. return index;
  25882. };
  25883. /**
  25884. * Removes the given effect layer from this scene.
  25885. * @param toRemove defines the effect layer to remove
  25886. * @returns the index of the removed effect layer
  25887. */
  25888. Scene.prototype.removeEffectLayer = function (toRemove) {
  25889. var index = this.effectLayers.indexOf(toRemove);
  25890. if (index !== -1) {
  25891. this.effectLayers.splice(index, 1);
  25892. }
  25893. return index;
  25894. };
  25895. /**
  25896. * Removes the given texture from this scene.
  25897. * @param toRemove The texture to remove
  25898. * @returns The index of the removed texture
  25899. */
  25900. Scene.prototype.removeTexture = function (toRemove) {
  25901. var index = this.textures.indexOf(toRemove);
  25902. if (index !== -1) {
  25903. this.textures.splice(index, 1);
  25904. }
  25905. return index;
  25906. };
  25907. /**
  25908. * Adds the given light to this scene
  25909. * @param newLight The light to add
  25910. */
  25911. Scene.prototype.addLight = function (newLight) {
  25912. this.lights.push(newLight);
  25913. this.sortLightsByPriority();
  25914. // Add light to all meshes (To support if the light is removed and then readded)
  25915. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25916. var mesh = _a[_i];
  25917. if (mesh._lightSources.indexOf(newLight) === -1) {
  25918. mesh._lightSources.push(newLight);
  25919. mesh._resyncLightSources();
  25920. }
  25921. }
  25922. this.onNewLightAddedObservable.notifyObservers(newLight);
  25923. };
  25924. /**
  25925. * Sorts the list list based on light priorities
  25926. */
  25927. Scene.prototype.sortLightsByPriority = function () {
  25928. if (this.requireLightSorting) {
  25929. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  25930. }
  25931. };
  25932. /**
  25933. * Adds the given camera to this scene
  25934. * @param newCamera The camera to add
  25935. */
  25936. Scene.prototype.addCamera = function (newCamera) {
  25937. this.cameras.push(newCamera);
  25938. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  25939. };
  25940. /**
  25941. * Adds the given skeleton to this scene
  25942. * @param newSkeleton The skeleton to add
  25943. */
  25944. Scene.prototype.addSkeleton = function (newSkeleton) {
  25945. this.skeletons.push(newSkeleton);
  25946. };
  25947. /**
  25948. * Adds the given particle system to this scene
  25949. * @param newParticleSystem The particle system to add
  25950. */
  25951. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  25952. this.particleSystems.push(newParticleSystem);
  25953. };
  25954. /**
  25955. * Adds the given animation to this scene
  25956. * @param newAnimation The animation to add
  25957. */
  25958. Scene.prototype.addAnimation = function (newAnimation) {
  25959. this.animations.push(newAnimation);
  25960. };
  25961. /**
  25962. * Adds the given animation group to this scene.
  25963. * @param newAnimationGroup The animation group to add
  25964. */
  25965. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  25966. this.animationGroups.push(newAnimationGroup);
  25967. };
  25968. /**
  25969. * Adds the given multi-material to this scene
  25970. * @param newMultiMaterial The multi-material to add
  25971. */
  25972. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  25973. this.multiMaterials.push(newMultiMaterial);
  25974. };
  25975. /**
  25976. * Adds the given material to this scene
  25977. * @param newMaterial The material to add
  25978. */
  25979. Scene.prototype.addMaterial = function (newMaterial) {
  25980. this.materials.push(newMaterial);
  25981. };
  25982. /**
  25983. * Adds the given morph target to this scene
  25984. * @param newMorphTargetManager The morph target to add
  25985. */
  25986. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  25987. this.morphTargetManagers.push(newMorphTargetManager);
  25988. };
  25989. /**
  25990. * Adds the given geometry to this scene
  25991. * @param newGeometry The geometry to add
  25992. */
  25993. Scene.prototype.addGeometry = function (newGeometry) {
  25994. this._geometries.push(newGeometry);
  25995. };
  25996. /**
  25997. * Adds the given lens flare system to this scene
  25998. * @param newLensFlareSystem The lens flare system to add
  25999. */
  26000. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26001. this.lensFlareSystems.push(newLensFlareSystem);
  26002. };
  26003. /**
  26004. * Adds the given effect layer to this scene
  26005. * @param newEffectLayer defines the effect layer to add
  26006. */
  26007. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26008. this.effectLayers.push(newEffectLayer);
  26009. };
  26010. /**
  26011. * Adds the given action manager to this scene
  26012. * @param newActionManager The action manager to add
  26013. */
  26014. Scene.prototype.addActionManager = function (newActionManager) {
  26015. this._actionManagers.push(newActionManager);
  26016. };
  26017. /**
  26018. * Adds the given texture to this scene.
  26019. * @param newTexture The texture to add
  26020. */
  26021. Scene.prototype.addTexture = function (newTexture) {
  26022. this.textures.push(newTexture);
  26023. };
  26024. /**
  26025. * Switch active camera
  26026. * @param newCamera defines the new active camera
  26027. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26028. */
  26029. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26030. if (attachControl === void 0) { attachControl = true; }
  26031. var canvas = this._engine.getRenderingCanvas();
  26032. if (!canvas) {
  26033. return;
  26034. }
  26035. if (this.activeCamera) {
  26036. this.activeCamera.detachControl(canvas);
  26037. }
  26038. this.activeCamera = newCamera;
  26039. if (attachControl) {
  26040. newCamera.attachControl(canvas);
  26041. }
  26042. };
  26043. /**
  26044. * sets the active camera of the scene using its ID
  26045. * @param id defines the camera's ID
  26046. * @return the new active camera or null if none found.
  26047. */
  26048. Scene.prototype.setActiveCameraByID = function (id) {
  26049. var camera = this.getCameraByID(id);
  26050. if (camera) {
  26051. this.activeCamera = camera;
  26052. return camera;
  26053. }
  26054. return null;
  26055. };
  26056. /**
  26057. * sets the active camera of the scene using its name
  26058. * @param name defines the camera's name
  26059. * @returns the new active camera or null if none found.
  26060. */
  26061. Scene.prototype.setActiveCameraByName = function (name) {
  26062. var camera = this.getCameraByName(name);
  26063. if (camera) {
  26064. this.activeCamera = camera;
  26065. return camera;
  26066. }
  26067. return null;
  26068. };
  26069. /**
  26070. * get an animation group using its name
  26071. * @param name defines the material's name
  26072. * @return the animation group or null if none found.
  26073. */
  26074. Scene.prototype.getAnimationGroupByName = function (name) {
  26075. for (var index = 0; index < this.animationGroups.length; index++) {
  26076. if (this.animationGroups[index].name === name) {
  26077. return this.animationGroups[index];
  26078. }
  26079. }
  26080. return null;
  26081. };
  26082. /**
  26083. * get a material using its id
  26084. * @param id defines the material's ID
  26085. * @return the material or null if none found.
  26086. */
  26087. Scene.prototype.getMaterialByID = function (id) {
  26088. for (var index = 0; index < this.materials.length; index++) {
  26089. if (this.materials[index].id === id) {
  26090. return this.materials[index];
  26091. }
  26092. }
  26093. return null;
  26094. };
  26095. /**
  26096. * Gets a material using its name
  26097. * @param name defines the material's name
  26098. * @return the material or null if none found.
  26099. */
  26100. Scene.prototype.getMaterialByName = function (name) {
  26101. for (var index = 0; index < this.materials.length; index++) {
  26102. if (this.materials[index].name === name) {
  26103. return this.materials[index];
  26104. }
  26105. }
  26106. return null;
  26107. };
  26108. /**
  26109. * Gets a lens flare system using its name
  26110. * @param name defines the name to look for
  26111. * @returns the lens flare system or null if not found
  26112. */
  26113. Scene.prototype.getLensFlareSystemByName = function (name) {
  26114. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26115. if (this.lensFlareSystems[index].name === name) {
  26116. return this.lensFlareSystems[index];
  26117. }
  26118. }
  26119. return null;
  26120. };
  26121. /**
  26122. * Gets a lens flare system using its id
  26123. * @param id defines the id to look for
  26124. * @returns the lens flare system or null if not found
  26125. */
  26126. Scene.prototype.getLensFlareSystemByID = function (id) {
  26127. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26128. if (this.lensFlareSystems[index].id === id) {
  26129. return this.lensFlareSystems[index];
  26130. }
  26131. }
  26132. return null;
  26133. };
  26134. /**
  26135. * Gets a camera using its id
  26136. * @param id defines the id to look for
  26137. * @returns the camera or null if not found
  26138. */
  26139. Scene.prototype.getCameraByID = function (id) {
  26140. for (var index = 0; index < this.cameras.length; index++) {
  26141. if (this.cameras[index].id === id) {
  26142. return this.cameras[index];
  26143. }
  26144. }
  26145. return null;
  26146. };
  26147. /**
  26148. * Gets a camera using its unique id
  26149. * @param uniqueId defines the unique id to look for
  26150. * @returns the camera or null if not found
  26151. */
  26152. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26153. for (var index = 0; index < this.cameras.length; index++) {
  26154. if (this.cameras[index].uniqueId === uniqueId) {
  26155. return this.cameras[index];
  26156. }
  26157. }
  26158. return null;
  26159. };
  26160. /**
  26161. * Gets a camera using its name
  26162. * @param name defines the camera's name
  26163. * @return the camera or null if none found.
  26164. */
  26165. Scene.prototype.getCameraByName = function (name) {
  26166. for (var index = 0; index < this.cameras.length; index++) {
  26167. if (this.cameras[index].name === name) {
  26168. return this.cameras[index];
  26169. }
  26170. }
  26171. return null;
  26172. };
  26173. /**
  26174. * Gets a bone using its id
  26175. * @param id defines the bone's id
  26176. * @return the bone or null if not found
  26177. */
  26178. Scene.prototype.getBoneByID = function (id) {
  26179. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26180. var skeleton = this.skeletons[skeletonIndex];
  26181. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26182. if (skeleton.bones[boneIndex].id === id) {
  26183. return skeleton.bones[boneIndex];
  26184. }
  26185. }
  26186. }
  26187. return null;
  26188. };
  26189. /**
  26190. * Gets a bone using its id
  26191. * @param name defines the bone's name
  26192. * @return the bone or null if not found
  26193. */
  26194. Scene.prototype.getBoneByName = function (name) {
  26195. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26196. var skeleton = this.skeletons[skeletonIndex];
  26197. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26198. if (skeleton.bones[boneIndex].name === name) {
  26199. return skeleton.bones[boneIndex];
  26200. }
  26201. }
  26202. }
  26203. return null;
  26204. };
  26205. /**
  26206. * Gets a light node using its name
  26207. * @param name defines the the light's name
  26208. * @return the light or null if none found.
  26209. */
  26210. Scene.prototype.getLightByName = function (name) {
  26211. for (var index = 0; index < this.lights.length; index++) {
  26212. if (this.lights[index].name === name) {
  26213. return this.lights[index];
  26214. }
  26215. }
  26216. return null;
  26217. };
  26218. /**
  26219. * Gets a light node using its id
  26220. * @param id defines the light's id
  26221. * @return the light or null if none found.
  26222. */
  26223. Scene.prototype.getLightByID = function (id) {
  26224. for (var index = 0; index < this.lights.length; index++) {
  26225. if (this.lights[index].id === id) {
  26226. return this.lights[index];
  26227. }
  26228. }
  26229. return null;
  26230. };
  26231. /**
  26232. * Gets a light node using its scene-generated unique ID
  26233. * @param uniqueId defines the light's unique id
  26234. * @return the light or null if none found.
  26235. */
  26236. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26237. for (var index = 0; index < this.lights.length; index++) {
  26238. if (this.lights[index].uniqueId === uniqueId) {
  26239. return this.lights[index];
  26240. }
  26241. }
  26242. return null;
  26243. };
  26244. /**
  26245. * Gets a particle system by id
  26246. * @param id defines the particle system id
  26247. * @return the corresponding system or null if none found
  26248. */
  26249. Scene.prototype.getParticleSystemByID = function (id) {
  26250. for (var index = 0; index < this.particleSystems.length; index++) {
  26251. if (this.particleSystems[index].id === id) {
  26252. return this.particleSystems[index];
  26253. }
  26254. }
  26255. return null;
  26256. };
  26257. /**
  26258. * Gets a geometry using its ID
  26259. * @param id defines the geometry's id
  26260. * @return the geometry or null if none found.
  26261. */
  26262. Scene.prototype.getGeometryByID = function (id) {
  26263. for (var index = 0; index < this._geometries.length; index++) {
  26264. if (this._geometries[index].id === id) {
  26265. return this._geometries[index];
  26266. }
  26267. }
  26268. return null;
  26269. };
  26270. /**
  26271. * Add a new geometry to this scene
  26272. * @param geometry defines the geometry to be added to the scene.
  26273. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26274. * @return a boolean defining if the geometry was added or not
  26275. */
  26276. Scene.prototype.pushGeometry = function (geometry, force) {
  26277. if (!force && this.getGeometryByID(geometry.id)) {
  26278. return false;
  26279. }
  26280. this._geometries.push(geometry);
  26281. //notify the collision coordinator
  26282. if (this.collisionCoordinator) {
  26283. this.collisionCoordinator.onGeometryAdded(geometry);
  26284. }
  26285. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26286. return true;
  26287. };
  26288. /**
  26289. * Removes an existing geometry
  26290. * @param geometry defines the geometry to be removed from the scene
  26291. * @return a boolean defining if the geometry was removed or not
  26292. */
  26293. Scene.prototype.removeGeometry = function (geometry) {
  26294. var index = this._geometries.indexOf(geometry);
  26295. if (index > -1) {
  26296. this._geometries.splice(index, 1);
  26297. //notify the collision coordinator
  26298. if (this.collisionCoordinator) {
  26299. this.collisionCoordinator.onGeometryDeleted(geometry);
  26300. }
  26301. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26302. return true;
  26303. }
  26304. return false;
  26305. };
  26306. /**
  26307. * Gets the list of geometries attached to the scene
  26308. * @returns an array of Geometry
  26309. */
  26310. Scene.prototype.getGeometries = function () {
  26311. return this._geometries;
  26312. };
  26313. /**
  26314. * Gets the first added mesh found of a given ID
  26315. * @param id defines the id to search for
  26316. * @return the mesh found or null if not found at all
  26317. */
  26318. Scene.prototype.getMeshByID = function (id) {
  26319. for (var index = 0; index < this.meshes.length; index++) {
  26320. if (this.meshes[index].id === id) {
  26321. return this.meshes[index];
  26322. }
  26323. }
  26324. return null;
  26325. };
  26326. /**
  26327. * Gets a list of meshes using their id
  26328. * @param id defines the id to search for
  26329. * @returns a list of meshes
  26330. */
  26331. Scene.prototype.getMeshesByID = function (id) {
  26332. return this.meshes.filter(function (m) {
  26333. return m.id === id;
  26334. });
  26335. };
  26336. /**
  26337. * Gets the first added transform node found of a given ID
  26338. * @param id defines the id to search for
  26339. * @return the found transform node or null if not found at all.
  26340. */
  26341. Scene.prototype.getTransformNodeByID = function (id) {
  26342. for (var index = 0; index < this.transformNodes.length; index++) {
  26343. if (this.transformNodes[index].id === id) {
  26344. return this.transformNodes[index];
  26345. }
  26346. }
  26347. return null;
  26348. };
  26349. /**
  26350. * Gets a list of transform nodes using their id
  26351. * @param id defines the id to search for
  26352. * @returns a list of transform nodes
  26353. */
  26354. Scene.prototype.getTransformNodesByID = function (id) {
  26355. return this.transformNodes.filter(function (m) {
  26356. return m.id === id;
  26357. });
  26358. };
  26359. /**
  26360. * Gets a mesh with its auto-generated unique id
  26361. * @param uniqueId defines the unique id to search for
  26362. * @return the found mesh or null if not found at all.
  26363. */
  26364. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26365. for (var index = 0; index < this.meshes.length; index++) {
  26366. if (this.meshes[index].uniqueId === uniqueId) {
  26367. return this.meshes[index];
  26368. }
  26369. }
  26370. return null;
  26371. };
  26372. /**
  26373. * Gets a the last added mesh using a given id
  26374. * @param id defines the id to search for
  26375. * @return the found mesh or null if not found at all.
  26376. */
  26377. Scene.prototype.getLastMeshByID = function (id) {
  26378. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26379. if (this.meshes[index].id === id) {
  26380. return this.meshes[index];
  26381. }
  26382. }
  26383. return null;
  26384. };
  26385. /**
  26386. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26387. * @param id defines the id to search for
  26388. * @return the found node or null if not found at all
  26389. */
  26390. Scene.prototype.getLastEntryByID = function (id) {
  26391. var index;
  26392. for (index = this.meshes.length - 1; index >= 0; index--) {
  26393. if (this.meshes[index].id === id) {
  26394. return this.meshes[index];
  26395. }
  26396. }
  26397. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26398. if (this.transformNodes[index].id === id) {
  26399. return this.transformNodes[index];
  26400. }
  26401. }
  26402. for (index = this.cameras.length - 1; index >= 0; index--) {
  26403. if (this.cameras[index].id === id) {
  26404. return this.cameras[index];
  26405. }
  26406. }
  26407. for (index = this.lights.length - 1; index >= 0; index--) {
  26408. if (this.lights[index].id === id) {
  26409. return this.lights[index];
  26410. }
  26411. }
  26412. return null;
  26413. };
  26414. /**
  26415. * Gets a node (Mesh, Camera, Light) using a given id
  26416. * @param id defines the id to search for
  26417. * @return the found node or null if not found at all
  26418. */
  26419. Scene.prototype.getNodeByID = function (id) {
  26420. var mesh = this.getMeshByID(id);
  26421. if (mesh) {
  26422. return mesh;
  26423. }
  26424. var light = this.getLightByID(id);
  26425. if (light) {
  26426. return light;
  26427. }
  26428. var camera = this.getCameraByID(id);
  26429. if (camera) {
  26430. return camera;
  26431. }
  26432. var bone = this.getBoneByID(id);
  26433. return bone;
  26434. };
  26435. /**
  26436. * Gets a node (Mesh, Camera, Light) using a given name
  26437. * @param name defines the name to search for
  26438. * @return the found node or null if not found at all.
  26439. */
  26440. Scene.prototype.getNodeByName = function (name) {
  26441. var mesh = this.getMeshByName(name);
  26442. if (mesh) {
  26443. return mesh;
  26444. }
  26445. var light = this.getLightByName(name);
  26446. if (light) {
  26447. return light;
  26448. }
  26449. var camera = this.getCameraByName(name);
  26450. if (camera) {
  26451. return camera;
  26452. }
  26453. var bone = this.getBoneByName(name);
  26454. return bone;
  26455. };
  26456. /**
  26457. * Gets a mesh using a given name
  26458. * @param name defines the name to search for
  26459. * @return the found mesh or null if not found at all.
  26460. */
  26461. Scene.prototype.getMeshByName = function (name) {
  26462. for (var index = 0; index < this.meshes.length; index++) {
  26463. if (this.meshes[index].name === name) {
  26464. return this.meshes[index];
  26465. }
  26466. }
  26467. return null;
  26468. };
  26469. /**
  26470. * Gets a transform node using a given name
  26471. * @param name defines the name to search for
  26472. * @return the found transform node or null if not found at all.
  26473. */
  26474. Scene.prototype.getTransformNodeByName = function (name) {
  26475. for (var index = 0; index < this.transformNodes.length; index++) {
  26476. if (this.transformNodes[index].name === name) {
  26477. return this.transformNodes[index];
  26478. }
  26479. }
  26480. return null;
  26481. };
  26482. /**
  26483. * Gets a sound using a given name
  26484. * @param name defines the name to search for
  26485. * @return the found sound or null if not found at all.
  26486. */
  26487. Scene.prototype.getSoundByName = function (name) {
  26488. var index;
  26489. if (BABYLON.AudioEngine) {
  26490. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26491. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26492. return this.mainSoundTrack.soundCollection[index];
  26493. }
  26494. }
  26495. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26496. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26497. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26498. return this.soundTracks[sdIndex].soundCollection[index];
  26499. }
  26500. }
  26501. }
  26502. }
  26503. return null;
  26504. };
  26505. /**
  26506. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26507. * @param id defines the id to search for
  26508. * @return the found skeleton or null if not found at all.
  26509. */
  26510. Scene.prototype.getLastSkeletonByID = function (id) {
  26511. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26512. if (this.skeletons[index].id === id) {
  26513. return this.skeletons[index];
  26514. }
  26515. }
  26516. return null;
  26517. };
  26518. /**
  26519. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26520. * @param id defines the id to search for
  26521. * @return the found skeleton or null if not found at all.
  26522. */
  26523. Scene.prototype.getSkeletonById = function (id) {
  26524. for (var index = 0; index < this.skeletons.length; index++) {
  26525. if (this.skeletons[index].id === id) {
  26526. return this.skeletons[index];
  26527. }
  26528. }
  26529. return null;
  26530. };
  26531. /**
  26532. * Gets a skeleton using a given name
  26533. * @param name defines the name to search for
  26534. * @return the found skeleton or null if not found at all.
  26535. */
  26536. Scene.prototype.getSkeletonByName = function (name) {
  26537. for (var index = 0; index < this.skeletons.length; index++) {
  26538. if (this.skeletons[index].name === name) {
  26539. return this.skeletons[index];
  26540. }
  26541. }
  26542. return null;
  26543. };
  26544. /**
  26545. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26546. * @param id defines the id to search for
  26547. * @return the found morph target manager or null if not found at all.
  26548. */
  26549. Scene.prototype.getMorphTargetManagerById = function (id) {
  26550. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26551. if (this.morphTargetManagers[index].uniqueId === id) {
  26552. return this.morphTargetManagers[index];
  26553. }
  26554. }
  26555. return null;
  26556. };
  26557. /**
  26558. * Gets a boolean indicating if the given mesh is active
  26559. * @param mesh defines the mesh to look for
  26560. * @returns true if the mesh is in the active list
  26561. */
  26562. Scene.prototype.isActiveMesh = function (mesh) {
  26563. return (this._activeMeshes.indexOf(mesh) !== -1);
  26564. };
  26565. /**
  26566. * Return a the first highlight layer of the scene with a given name.
  26567. * @param name The name of the highlight layer to look for.
  26568. * @return The highlight layer if found otherwise null.
  26569. */
  26570. Scene.prototype.getHighlightLayerByName = function (name) {
  26571. for (var index = 0; index < this.effectLayers.length; index++) {
  26572. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26573. return this.effectLayers[index];
  26574. }
  26575. }
  26576. return null;
  26577. };
  26578. /**
  26579. * Return a the first highlight layer of the scene with a given name.
  26580. * @param name The name of the highlight layer to look for.
  26581. * @return The highlight layer if found otherwise null.
  26582. */
  26583. Scene.prototype.getGlowLayerByName = function (name) {
  26584. for (var index = 0; index < this.effectLayers.length; index++) {
  26585. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26586. return this.effectLayers[index];
  26587. }
  26588. }
  26589. return null;
  26590. };
  26591. Object.defineProperty(Scene.prototype, "uid", {
  26592. /**
  26593. * Return a unique id as a string which can serve as an identifier for the scene
  26594. */
  26595. get: function () {
  26596. if (!this._uid) {
  26597. this._uid = BABYLON.Tools.RandomId();
  26598. }
  26599. return this._uid;
  26600. },
  26601. enumerable: true,
  26602. configurable: true
  26603. });
  26604. /**
  26605. * Add an externaly attached data from its key.
  26606. * This method call will fail and return false, if such key already exists.
  26607. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26608. * @param key the unique key that identifies the data
  26609. * @param data the data object to associate to the key for this Engine instance
  26610. * @return true if no such key were already present and the data was added successfully, false otherwise
  26611. */
  26612. Scene.prototype.addExternalData = function (key, data) {
  26613. if (!this._externalData) {
  26614. this._externalData = new BABYLON.StringDictionary();
  26615. }
  26616. return this._externalData.add(key, data);
  26617. };
  26618. /**
  26619. * Get an externaly attached data from its key
  26620. * @param key the unique key that identifies the data
  26621. * @return the associated data, if present (can be null), or undefined if not present
  26622. */
  26623. Scene.prototype.getExternalData = function (key) {
  26624. if (!this._externalData) {
  26625. return null;
  26626. }
  26627. return this._externalData.get(key);
  26628. };
  26629. /**
  26630. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26631. * @param key the unique key that identifies the data
  26632. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26633. * @return the associated data, can be null if the factory returned null.
  26634. */
  26635. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26636. if (!this._externalData) {
  26637. this._externalData = new BABYLON.StringDictionary();
  26638. }
  26639. return this._externalData.getOrAddWithFactory(key, factory);
  26640. };
  26641. /**
  26642. * Remove an externaly attached data from the Engine instance
  26643. * @param key the unique key that identifies the data
  26644. * @return true if the data was successfully removed, false if it doesn't exist
  26645. */
  26646. Scene.prototype.removeExternalData = function (key) {
  26647. return this._externalData.remove(key);
  26648. };
  26649. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26650. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26651. if (mesh.showSubMeshesBoundingBox) {
  26652. var boundingInfo = subMesh.getBoundingInfo();
  26653. if (boundingInfo !== null && boundingInfo !== undefined) {
  26654. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26655. }
  26656. }
  26657. var material = subMesh.getMaterial();
  26658. if (material !== null && material !== undefined) {
  26659. // Render targets
  26660. if (material.getRenderTargetTextures !== undefined) {
  26661. if (this._processedMaterials.indexOf(material) === -1) {
  26662. this._processedMaterials.push(material);
  26663. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26664. }
  26665. }
  26666. // Dispatch
  26667. this._activeIndices.addCount(subMesh.indexCount, false);
  26668. this._renderingManager.dispatch(subMesh, mesh, material);
  26669. }
  26670. }
  26671. };
  26672. /**
  26673. * Clear the processed materials smart array preventing retention point in material dispose.
  26674. */
  26675. Scene.prototype.freeProcessedMaterials = function () {
  26676. this._processedMaterials.dispose();
  26677. };
  26678. /**
  26679. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26680. */
  26681. Scene.prototype.freeActiveMeshes = function () {
  26682. this._activeMeshes.dispose();
  26683. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26684. this.activeCamera._activeMeshes.dispose();
  26685. }
  26686. if (this.activeCameras) {
  26687. for (var i = 0; i < this.activeCameras.length; i++) {
  26688. var activeCamera = this.activeCameras[i];
  26689. if (activeCamera && activeCamera._activeMeshes) {
  26690. activeCamera._activeMeshes.dispose();
  26691. }
  26692. }
  26693. }
  26694. };
  26695. /**
  26696. * Clear the info related to rendering groups preventing retention points during dispose.
  26697. */
  26698. Scene.prototype.freeRenderingGroups = function () {
  26699. if (this._renderingManager) {
  26700. this._renderingManager.freeRenderingGroups();
  26701. }
  26702. if (this.textures) {
  26703. for (var i = 0; i < this.textures.length; i++) {
  26704. var texture = this.textures[i];
  26705. if (texture && texture.renderList) {
  26706. texture.freeRenderingGroups();
  26707. }
  26708. }
  26709. }
  26710. };
  26711. /** @ignore */
  26712. Scene.prototype._isInIntermediateRendering = function () {
  26713. return this._intermediateRendering;
  26714. };
  26715. /**
  26716. * Defines the current active mesh candidate provider
  26717. * @param provider defines the provider to use
  26718. */
  26719. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26720. this._activeMeshCandidateProvider = provider;
  26721. };
  26722. /**
  26723. * Gets the current active mesh candidate provider
  26724. * @returns the current active mesh candidate provider
  26725. */
  26726. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26727. return this._activeMeshCandidateProvider;
  26728. };
  26729. /**
  26730. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26731. * @returns the current scene
  26732. */
  26733. Scene.prototype.freezeActiveMeshes = function () {
  26734. if (!this.activeCamera) {
  26735. return this;
  26736. }
  26737. if (!this._frustumPlanes) {
  26738. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26739. }
  26740. this._evaluateActiveMeshes();
  26741. this._activeMeshesFrozen = true;
  26742. return this;
  26743. };
  26744. /**
  26745. * Use this function to restart evaluating active meshes on every frame
  26746. * @returns the current scene
  26747. */
  26748. Scene.prototype.unfreezeActiveMeshes = function () {
  26749. this._activeMeshesFrozen = false;
  26750. return this;
  26751. };
  26752. Scene.prototype._evaluateActiveMeshes = function () {
  26753. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26754. return;
  26755. }
  26756. if (!this.activeCamera) {
  26757. return;
  26758. }
  26759. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26760. this.activeCamera._activeMeshes.reset();
  26761. this._activeMeshes.reset();
  26762. this._renderingManager.reset();
  26763. this._processedMaterials.reset();
  26764. this._activeParticleSystems.reset();
  26765. this._activeSkeletons.reset();
  26766. this._softwareSkinnedMeshes.reset();
  26767. if (this._boundingBoxRenderer) {
  26768. this._boundingBoxRenderer.reset();
  26769. }
  26770. // Meshes
  26771. var meshes;
  26772. var len;
  26773. var checkIsEnabled = true;
  26774. // Determine mesh candidates
  26775. if (this._activeMeshCandidateProvider !== undefined) {
  26776. // Use _activeMeshCandidateProvider
  26777. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26778. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26779. if (meshes !== undefined) {
  26780. len = meshes.length;
  26781. }
  26782. else {
  26783. len = 0;
  26784. }
  26785. }
  26786. else if (this._selectionOctree !== undefined) {
  26787. // Octree
  26788. var selection = this._selectionOctree.select(this._frustumPlanes);
  26789. meshes = selection.data;
  26790. len = selection.length;
  26791. }
  26792. else {
  26793. // Full scene traversal
  26794. len = this.meshes.length;
  26795. meshes = this.meshes;
  26796. }
  26797. // Check each mesh
  26798. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26799. mesh = meshes[meshIndex];
  26800. if (mesh.isBlocked) {
  26801. continue;
  26802. }
  26803. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26804. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26805. continue;
  26806. }
  26807. mesh.computeWorldMatrix();
  26808. // Intersections
  26809. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26810. this._meshesForIntersections.pushNoDuplicate(mesh);
  26811. }
  26812. // Switch to current LOD
  26813. meshLOD = mesh.getLOD(this.activeCamera);
  26814. if (meshLOD === undefined || meshLOD === null) {
  26815. continue;
  26816. }
  26817. mesh._preActivate();
  26818. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26819. this._activeMeshes.push(mesh);
  26820. this.activeCamera._activeMeshes.push(mesh);
  26821. mesh._activate(this._renderId);
  26822. if (meshLOD !== mesh) {
  26823. meshLOD._activate(this._renderId);
  26824. }
  26825. this._activeMesh(mesh, meshLOD);
  26826. }
  26827. }
  26828. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26829. // Particle systems
  26830. if (this.particlesEnabled) {
  26831. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26832. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26833. var particleSystem = this.particleSystems[particleIndex];
  26834. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26835. continue;
  26836. }
  26837. var emitter = particleSystem.emitter;
  26838. if (!emitter.position || emitter.isEnabled()) {
  26839. this._activeParticleSystems.push(particleSystem);
  26840. particleSystem.animate();
  26841. this._renderingManager.dispatchParticles(particleSystem);
  26842. }
  26843. }
  26844. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26845. }
  26846. };
  26847. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26848. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26849. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26850. mesh.skeleton.prepare();
  26851. }
  26852. if (!mesh.computeBonesUsingShaders) {
  26853. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26854. }
  26855. }
  26856. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26857. var boundingInfo = sourceMesh.getBoundingInfo();
  26858. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26859. }
  26860. if (mesh !== undefined && mesh !== null
  26861. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26862. // Submeshes Octrees
  26863. var len;
  26864. var subMeshes;
  26865. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26866. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26867. len = intersections.length;
  26868. subMeshes = intersections.data;
  26869. }
  26870. else {
  26871. subMeshes = mesh.subMeshes;
  26872. len = subMeshes.length;
  26873. }
  26874. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  26875. subMesh = subMeshes[subIndex];
  26876. this._evaluateSubMesh(subMesh, mesh);
  26877. }
  26878. }
  26879. };
  26880. /**
  26881. * Update the transform matrix to update from the current active camera
  26882. * @param force defines a boolean used to force the update even if cache is up to date
  26883. */
  26884. Scene.prototype.updateTransformMatrix = function (force) {
  26885. if (!this.activeCamera) {
  26886. return;
  26887. }
  26888. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  26889. };
  26890. /**
  26891. * 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)
  26892. * @param alternateCamera defines the camera to use
  26893. */
  26894. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  26895. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  26896. };
  26897. Scene.prototype._renderForCamera = function (camera, rigParent) {
  26898. if (camera && camera._skipRendering) {
  26899. return;
  26900. }
  26901. var engine = this._engine;
  26902. this.activeCamera = camera;
  26903. if (!this.activeCamera)
  26904. throw new Error("Active camera not set");
  26905. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  26906. // Viewport
  26907. engine.setViewport(this.activeCamera.viewport);
  26908. // Camera
  26909. this.resetCachedMaterial();
  26910. this._renderId++;
  26911. this.updateTransformMatrix();
  26912. if (camera._alternateCamera) {
  26913. this.updateAlternateTransformMatrix(camera._alternateCamera);
  26914. this._alternateRendering = true;
  26915. }
  26916. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  26917. // Meshes
  26918. this._evaluateActiveMeshes();
  26919. // Software skinning
  26920. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  26921. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  26922. mesh.applySkeleton(mesh.skeleton);
  26923. }
  26924. // Render targets
  26925. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  26926. var needsRestoreFrameBuffer = false;
  26927. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  26928. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  26929. }
  26930. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  26931. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  26932. }
  26933. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  26934. this._intermediateRendering = true;
  26935. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26936. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  26937. var renderTarget = this._renderTargets.data[renderIndex];
  26938. if (renderTarget._shouldRender()) {
  26939. this._renderId++;
  26940. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  26941. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  26942. }
  26943. }
  26944. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  26945. this._intermediateRendering = false;
  26946. this._renderId++;
  26947. needsRestoreFrameBuffer = true; // Restore back buffer
  26948. }
  26949. // Render EffecttLayer Texture
  26950. var stencilState = this._engine.getStencilBuffer();
  26951. var renderEffects = false;
  26952. var needStencil = false;
  26953. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  26954. this._intermediateRendering = true;
  26955. for (var i = 0; i < this.effectLayers.length; i++) {
  26956. var effectLayer = this.effectLayers[i];
  26957. if (effectLayer.shouldRender() &&
  26958. (!effectLayer.camera ||
  26959. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  26960. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  26961. renderEffects = true;
  26962. needStencil = needStencil || effectLayer.needStencil();
  26963. var renderTarget = effectLayer._mainTexture;
  26964. if (renderTarget._shouldRender()) {
  26965. this._renderId++;
  26966. renderTarget.render(false, false);
  26967. needsRestoreFrameBuffer = true;
  26968. }
  26969. }
  26970. }
  26971. this._intermediateRendering = false;
  26972. this._renderId++;
  26973. }
  26974. if (needsRestoreFrameBuffer) {
  26975. engine.restoreDefaultFramebuffer(); // Restore back buffer
  26976. }
  26977. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  26978. // Prepare Frame
  26979. this.postProcessManager._prepareFrame();
  26980. // Backgrounds
  26981. var layerIndex;
  26982. var layer;
  26983. if (this.layers.length) {
  26984. engine.setDepthBuffer(false);
  26985. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  26986. layer = this.layers[layerIndex];
  26987. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  26988. layer.render();
  26989. }
  26990. }
  26991. engine.setDepthBuffer(true);
  26992. }
  26993. // Activate effect Layer stencil
  26994. if (needStencil) {
  26995. this._engine.setStencilBuffer(true);
  26996. }
  26997. // Render
  26998. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  26999. this._renderingManager.render(null, null, true, true);
  27000. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27001. // Restore effect Layer stencil
  27002. if (needStencil) {
  27003. this._engine.setStencilBuffer(stencilState);
  27004. }
  27005. // Bounding boxes
  27006. if (this._boundingBoxRenderer) {
  27007. this._boundingBoxRenderer.render();
  27008. }
  27009. // Lens flares
  27010. if (this.lensFlaresEnabled) {
  27011. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27012. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27013. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27014. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27015. lensFlareSystem.render();
  27016. }
  27017. }
  27018. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27019. }
  27020. // Effect Layer
  27021. if (renderEffects) {
  27022. engine.setDepthBuffer(false);
  27023. for (var i = 0; i < this.effectLayers.length; i++) {
  27024. if (this.effectLayers[i].shouldRender()) {
  27025. this.effectLayers[i].render();
  27026. }
  27027. }
  27028. engine.setDepthBuffer(true);
  27029. }
  27030. // Foregrounds
  27031. if (this.layers.length) {
  27032. engine.setDepthBuffer(false);
  27033. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27034. layer = this.layers[layerIndex];
  27035. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27036. layer.render();
  27037. }
  27038. }
  27039. engine.setDepthBuffer(true);
  27040. }
  27041. // Finalize frame
  27042. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27043. // Reset some special arrays
  27044. this._renderTargets.reset();
  27045. this._alternateRendering = false;
  27046. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27047. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27048. };
  27049. Scene.prototype._processSubCameras = function (camera) {
  27050. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27051. this._renderForCamera(camera);
  27052. return;
  27053. }
  27054. // rig cameras
  27055. for (var index = 0; index < camera._rigCameras.length; index++) {
  27056. this._renderForCamera(camera._rigCameras[index], camera);
  27057. }
  27058. this.activeCamera = camera;
  27059. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27060. };
  27061. Scene.prototype._checkIntersections = function () {
  27062. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27063. var sourceMesh = this._meshesForIntersections.data[index];
  27064. if (!sourceMesh.actionManager) {
  27065. continue;
  27066. }
  27067. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27068. var action = sourceMesh.actionManager.actions[actionIndex];
  27069. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27070. var parameters = action.getTriggerParameter();
  27071. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27072. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27073. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27074. if (areIntersecting && currentIntersectionInProgress === -1) {
  27075. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27076. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27077. sourceMesh._intersectionsInProgress.push(otherMesh);
  27078. }
  27079. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27080. sourceMesh._intersectionsInProgress.push(otherMesh);
  27081. }
  27082. }
  27083. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27084. //They intersected, and now they don't.
  27085. //is this trigger an exit trigger? execute an event.
  27086. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27087. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27088. }
  27089. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27090. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27091. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27092. return otherMesh === parameterMesh;
  27093. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27094. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27095. }
  27096. }
  27097. }
  27098. }
  27099. }
  27100. };
  27101. /**
  27102. * Render the scene
  27103. */
  27104. Scene.prototype.render = function () {
  27105. if (this.isDisposed) {
  27106. return;
  27107. }
  27108. this._activeParticles.fetchNewFrame();
  27109. this._totalVertices.fetchNewFrame();
  27110. this._activeIndices.fetchNewFrame();
  27111. this._activeBones.fetchNewFrame();
  27112. this._meshesForIntersections.reset();
  27113. this.resetCachedMaterial();
  27114. this.onBeforeAnimationsObservable.notifyObservers(this);
  27115. // Actions
  27116. if (this.actionManager) {
  27117. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27118. }
  27119. //Simplification Queue
  27120. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27121. this.simplificationQueue.executeNext();
  27122. }
  27123. if (this._engine.isDeterministicLockStep()) {
  27124. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27125. var defaultFPS = (60.0 / 1000.0);
  27126. var defaultFrameTime = 1000 / 60; // frame time in MS
  27127. if (this._physicsEngine) {
  27128. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27129. }
  27130. var stepsTaken = 0;
  27131. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27132. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27133. internalSteps = Math.min(internalSteps, maxSubSteps);
  27134. do {
  27135. this.onBeforeStepObservable.notifyObservers(this);
  27136. // Animations
  27137. this._animationRatio = defaultFrameTime * defaultFPS;
  27138. this._animate();
  27139. this.onAfterAnimationsObservable.notifyObservers(this);
  27140. // Physics
  27141. if (this._physicsEngine) {
  27142. this.onBeforePhysicsObservable.notifyObservers(this);
  27143. this._physicsEngine._step(defaultFrameTime / 1000);
  27144. this.onAfterPhysicsObservable.notifyObservers(this);
  27145. }
  27146. this.onAfterStepObservable.notifyObservers(this);
  27147. this._currentStepId++;
  27148. stepsTaken++;
  27149. deltaTime -= defaultFrameTime;
  27150. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27151. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27152. }
  27153. else {
  27154. // Animations
  27155. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27156. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27157. this._animate();
  27158. this.onAfterAnimationsObservable.notifyObservers(this);
  27159. // Physics
  27160. if (this._physicsEngine) {
  27161. this.onBeforePhysicsObservable.notifyObservers(this);
  27162. this._physicsEngine._step(deltaTime / 1000.0);
  27163. this.onAfterPhysicsObservable.notifyObservers(this);
  27164. }
  27165. }
  27166. // update gamepad manager
  27167. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27168. this._gamepadManager._checkGamepadsStatus();
  27169. }
  27170. // Update Cameras
  27171. if (this.activeCameras.length > 0) {
  27172. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27173. var camera = this.activeCameras[cameraIndex];
  27174. camera.update();
  27175. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27176. // rig cameras
  27177. for (var index = 0; index < camera._rigCameras.length; index++) {
  27178. camera._rigCameras[index].update();
  27179. }
  27180. }
  27181. }
  27182. }
  27183. else if (this.activeCamera) {
  27184. this.activeCamera.update();
  27185. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27186. // rig cameras
  27187. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27188. this.activeCamera._rigCameras[index].update();
  27189. }
  27190. }
  27191. }
  27192. // Before render
  27193. this.onBeforeRenderObservable.notifyObservers(this);
  27194. // Customs render targets
  27195. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27196. var engine = this.getEngine();
  27197. var currentActiveCamera = this.activeCamera;
  27198. if (this.renderTargetsEnabled) {
  27199. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27200. this._intermediateRendering = true;
  27201. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27202. var renderTarget = this.customRenderTargets[customIndex];
  27203. if (renderTarget._shouldRender()) {
  27204. this._renderId++;
  27205. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27206. if (!this.activeCamera)
  27207. throw new Error("Active camera not set");
  27208. // Viewport
  27209. engine.setViewport(this.activeCamera.viewport);
  27210. // Camera
  27211. this.updateTransformMatrix();
  27212. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27213. }
  27214. }
  27215. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27216. this._intermediateRendering = false;
  27217. this._renderId++;
  27218. }
  27219. // Restore back buffer
  27220. if (this.customRenderTargets.length > 0) {
  27221. engine.restoreDefaultFramebuffer();
  27222. }
  27223. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27224. this.activeCamera = currentActiveCamera;
  27225. // Procedural textures
  27226. if (this.proceduralTexturesEnabled) {
  27227. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27228. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27229. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27230. if (proceduralTexture._shouldRender()) {
  27231. proceduralTexture.render();
  27232. }
  27233. }
  27234. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27235. }
  27236. // Clear
  27237. if (this.autoClearDepthAndStencil || this.autoClear) {
  27238. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27239. }
  27240. // Shadows
  27241. if (this.shadowsEnabled) {
  27242. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27243. var light = this.lights[lightIndex];
  27244. var shadowGenerator = light.getShadowGenerator();
  27245. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27246. var shadowMap = (shadowGenerator.getShadowMap());
  27247. if (this.textures.indexOf(shadowMap) !== -1) {
  27248. this._renderTargets.push(shadowMap);
  27249. }
  27250. }
  27251. }
  27252. }
  27253. // Depth renderer
  27254. for (var key in this._depthRenderer) {
  27255. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27256. }
  27257. // Geometry renderer
  27258. if (this._geometryBufferRenderer) {
  27259. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27260. }
  27261. // RenderPipeline
  27262. if (this._postProcessRenderPipelineManager) {
  27263. this._postProcessRenderPipelineManager.update();
  27264. }
  27265. // Multi-cameras?
  27266. if (this.activeCameras.length > 0) {
  27267. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27268. if (cameraIndex > 0) {
  27269. this._engine.clear(null, false, true, true);
  27270. }
  27271. this._processSubCameras(this.activeCameras[cameraIndex]);
  27272. }
  27273. }
  27274. else {
  27275. if (!this.activeCamera) {
  27276. throw new Error("No camera defined");
  27277. }
  27278. this._processSubCameras(this.activeCamera);
  27279. }
  27280. // Intersection checks
  27281. this._checkIntersections();
  27282. // Update the audio listener attached to the camera
  27283. if (BABYLON.AudioEngine) {
  27284. this._updateAudioParameters();
  27285. }
  27286. // After render
  27287. if (this.afterRender) {
  27288. this.afterRender();
  27289. }
  27290. this.onAfterRenderObservable.notifyObservers(this);
  27291. // Cleaning
  27292. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27293. var data = this._toBeDisposed.data[index];
  27294. if (data) {
  27295. data.dispose();
  27296. }
  27297. this._toBeDisposed[index] = null;
  27298. }
  27299. this._toBeDisposed.reset();
  27300. if (this.dumpNextRenderTargets) {
  27301. this.dumpNextRenderTargets = false;
  27302. }
  27303. this._activeBones.addCount(0, true);
  27304. this._activeIndices.addCount(0, true);
  27305. this._activeParticles.addCount(0, true);
  27306. };
  27307. Scene.prototype._updateAudioParameters = function () {
  27308. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27309. return;
  27310. }
  27311. var listeningCamera;
  27312. var audioEngine = BABYLON.Engine.audioEngine;
  27313. if (this.activeCameras.length > 0) {
  27314. listeningCamera = this.activeCameras[0];
  27315. }
  27316. else {
  27317. listeningCamera = this.activeCamera;
  27318. }
  27319. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27320. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27321. // for VR cameras
  27322. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27323. listeningCamera = listeningCamera.rigCameras[0];
  27324. }
  27325. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27326. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27327. cameraDirection.normalize();
  27328. // To avoid some errors on GearVR
  27329. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27330. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27331. }
  27332. var i;
  27333. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27334. var sound = this.mainSoundTrack.soundCollection[i];
  27335. if (sound.useCustomAttenuation) {
  27336. sound.updateDistanceFromListener();
  27337. }
  27338. }
  27339. for (i = 0; i < this.soundTracks.length; i++) {
  27340. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27341. sound = this.soundTracks[i].soundCollection[j];
  27342. if (sound.useCustomAttenuation) {
  27343. sound.updateDistanceFromListener();
  27344. }
  27345. }
  27346. }
  27347. }
  27348. };
  27349. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27350. // Audio
  27351. /**
  27352. * Gets or sets if audio support is enabled
  27353. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27354. */
  27355. get: function () {
  27356. return this._audioEnabled;
  27357. },
  27358. set: function (value) {
  27359. this._audioEnabled = value;
  27360. if (BABYLON.AudioEngine) {
  27361. if (this._audioEnabled) {
  27362. this._enableAudio();
  27363. }
  27364. else {
  27365. this._disableAudio();
  27366. }
  27367. }
  27368. },
  27369. enumerable: true,
  27370. configurable: true
  27371. });
  27372. Scene.prototype._disableAudio = function () {
  27373. var i;
  27374. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27375. this.mainSoundTrack.soundCollection[i].pause();
  27376. }
  27377. for (i = 0; i < this.soundTracks.length; i++) {
  27378. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27379. this.soundTracks[i].soundCollection[j].pause();
  27380. }
  27381. }
  27382. };
  27383. Scene.prototype._enableAudio = function () {
  27384. var i;
  27385. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27386. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27387. this.mainSoundTrack.soundCollection[i].play();
  27388. }
  27389. }
  27390. for (i = 0; i < this.soundTracks.length; i++) {
  27391. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27392. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27393. this.soundTracks[i].soundCollection[j].play();
  27394. }
  27395. }
  27396. }
  27397. };
  27398. Object.defineProperty(Scene.prototype, "headphone", {
  27399. /**
  27400. * Gets or sets if audio will be output to headphones
  27401. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27402. */
  27403. get: function () {
  27404. return this._headphone;
  27405. },
  27406. set: function (value) {
  27407. this._headphone = value;
  27408. if (BABYLON.AudioEngine) {
  27409. if (this._headphone) {
  27410. this._switchAudioModeForHeadphones();
  27411. }
  27412. else {
  27413. this._switchAudioModeForNormalSpeakers();
  27414. }
  27415. }
  27416. },
  27417. enumerable: true,
  27418. configurable: true
  27419. });
  27420. Scene.prototype._switchAudioModeForHeadphones = function () {
  27421. this.mainSoundTrack.switchPanningModelToHRTF();
  27422. for (var i = 0; i < this.soundTracks.length; i++) {
  27423. this.soundTracks[i].switchPanningModelToHRTF();
  27424. }
  27425. };
  27426. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27427. this.mainSoundTrack.switchPanningModelToEqualPower();
  27428. for (var i = 0; i < this.soundTracks.length; i++) {
  27429. this.soundTracks[i].switchPanningModelToEqualPower();
  27430. }
  27431. };
  27432. /**
  27433. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27434. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27435. * @returns the created depth renderer
  27436. */
  27437. Scene.prototype.enableDepthRenderer = function (camera) {
  27438. camera = camera || this.activeCamera;
  27439. if (!camera) {
  27440. throw "No camera available to enable depth renderer";
  27441. }
  27442. if (!this._depthRenderer[camera.id]) {
  27443. var textureType = 0;
  27444. if (this._engine.getCaps().textureHalfFloatRender) {
  27445. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27446. }
  27447. else if (this._engine.getCaps().textureFloatRender) {
  27448. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27449. }
  27450. else {
  27451. throw "Depth renderer does not support int texture type";
  27452. }
  27453. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27454. }
  27455. return this._depthRenderer[camera.id];
  27456. };
  27457. /**
  27458. * Disables a depth renderer for a given camera
  27459. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27460. */
  27461. Scene.prototype.disableDepthRenderer = function (camera) {
  27462. camera = camera || this.activeCamera;
  27463. if (!camera || !this._depthRenderer[camera.id]) {
  27464. return;
  27465. }
  27466. this._depthRenderer[camera.id].dispose();
  27467. delete this._depthRenderer[camera.id];
  27468. };
  27469. /**
  27470. * Enables a GeometryBufferRender and associates it with the scene
  27471. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27472. * @returns the GeometryBufferRenderer
  27473. */
  27474. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27475. if (ratio === void 0) { ratio = 1; }
  27476. if (this._geometryBufferRenderer) {
  27477. return this._geometryBufferRenderer;
  27478. }
  27479. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27480. if (!this._geometryBufferRenderer.isSupported) {
  27481. this._geometryBufferRenderer = null;
  27482. }
  27483. return this._geometryBufferRenderer;
  27484. };
  27485. /**
  27486. * Disables the GeometryBufferRender associated with the scene
  27487. */
  27488. Scene.prototype.disableGeometryBufferRenderer = function () {
  27489. if (!this._geometryBufferRenderer) {
  27490. return;
  27491. }
  27492. this._geometryBufferRenderer.dispose();
  27493. this._geometryBufferRenderer = null;
  27494. };
  27495. /**
  27496. * Freeze all materials
  27497. * A frozen material will not be updatable but should be faster to render
  27498. */
  27499. Scene.prototype.freezeMaterials = function () {
  27500. for (var i = 0; i < this.materials.length; i++) {
  27501. this.materials[i].freeze();
  27502. }
  27503. };
  27504. /**
  27505. * Unfreeze all materials
  27506. * A frozen material will not be updatable but should be faster to render
  27507. */
  27508. Scene.prototype.unfreezeMaterials = function () {
  27509. for (var i = 0; i < this.materials.length; i++) {
  27510. this.materials[i].unfreeze();
  27511. }
  27512. };
  27513. /**
  27514. * Releases all held ressources
  27515. */
  27516. Scene.prototype.dispose = function () {
  27517. this.beforeRender = null;
  27518. this.afterRender = null;
  27519. this.skeletons = [];
  27520. this.morphTargetManagers = [];
  27521. this.importedMeshesFiles = new Array();
  27522. this.stopAllAnimations();
  27523. this.resetCachedMaterial();
  27524. for (var key in this._depthRenderer) {
  27525. this._depthRenderer[key].dispose();
  27526. }
  27527. if (this._gamepadManager) {
  27528. this._gamepadManager.dispose();
  27529. this._gamepadManager = null;
  27530. }
  27531. // Smart arrays
  27532. if (this.activeCamera) {
  27533. this.activeCamera._activeMeshes.dispose();
  27534. this.activeCamera = null;
  27535. }
  27536. this._activeMeshes.dispose();
  27537. this._renderingManager.dispose();
  27538. this._processedMaterials.dispose();
  27539. this._activeParticleSystems.dispose();
  27540. this._activeSkeletons.dispose();
  27541. this._softwareSkinnedMeshes.dispose();
  27542. this._renderTargets.dispose();
  27543. this._registeredForLateAnimationBindings.dispose();
  27544. if (this._boundingBoxRenderer) {
  27545. this._boundingBoxRenderer.dispose();
  27546. }
  27547. this._meshesForIntersections.dispose();
  27548. this._toBeDisposed.dispose();
  27549. // Abort active requests
  27550. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27551. var request = _a[_i];
  27552. request.abort();
  27553. }
  27554. // Debug layer
  27555. if (this._debugLayer) {
  27556. this._debugLayer.hide();
  27557. }
  27558. // Events
  27559. this.onDisposeObservable.notifyObservers(this);
  27560. this.onDisposeObservable.clear();
  27561. this.onBeforeRenderObservable.clear();
  27562. this.onAfterRenderObservable.clear();
  27563. this.onBeforeRenderTargetsRenderObservable.clear();
  27564. this.onAfterRenderTargetsRenderObservable.clear();
  27565. this.onAfterStepObservable.clear();
  27566. this.onBeforeStepObservable.clear();
  27567. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27568. this.onAfterActiveMeshesEvaluationObservable.clear();
  27569. this.onBeforeParticlesRenderingObservable.clear();
  27570. this.onAfterParticlesRenderingObservable.clear();
  27571. this.onBeforeSpritesRenderingObservable.clear();
  27572. this.onAfterSpritesRenderingObservable.clear();
  27573. this.onBeforeDrawPhaseObservable.clear();
  27574. this.onAfterDrawPhaseObservable.clear();
  27575. this.onBeforePhysicsObservable.clear();
  27576. this.onAfterPhysicsObservable.clear();
  27577. this.onBeforeAnimationsObservable.clear();
  27578. this.onAfterAnimationsObservable.clear();
  27579. this.onDataLoadedObservable.clear();
  27580. this.detachControl();
  27581. // Release sounds & sounds tracks
  27582. if (BABYLON.AudioEngine) {
  27583. this.disposeSounds();
  27584. }
  27585. // VR Helper
  27586. if (this.VRHelper) {
  27587. this.VRHelper.dispose();
  27588. }
  27589. // Detach cameras
  27590. var canvas = this._engine.getRenderingCanvas();
  27591. if (canvas) {
  27592. var index;
  27593. for (index = 0; index < this.cameras.length; index++) {
  27594. this.cameras[index].detachControl(canvas);
  27595. }
  27596. }
  27597. // Release animation groups
  27598. while (this.animationGroups.length) {
  27599. this.animationGroups[0].dispose();
  27600. }
  27601. // Release lights
  27602. while (this.lights.length) {
  27603. this.lights[0].dispose();
  27604. }
  27605. // Release meshes
  27606. while (this.meshes.length) {
  27607. this.meshes[0].dispose(true);
  27608. }
  27609. while (this.transformNodes.length) {
  27610. this.removeTransformNode(this.transformNodes[0]);
  27611. }
  27612. // Release cameras
  27613. while (this.cameras.length) {
  27614. this.cameras[0].dispose();
  27615. }
  27616. // Release materials
  27617. if (this.defaultMaterial) {
  27618. this.defaultMaterial.dispose();
  27619. }
  27620. while (this.multiMaterials.length) {
  27621. this.multiMaterials[0].dispose();
  27622. }
  27623. while (this.materials.length) {
  27624. this.materials[0].dispose();
  27625. }
  27626. // Release particles
  27627. while (this.particleSystems.length) {
  27628. this.particleSystems[0].dispose();
  27629. }
  27630. // Release sprites
  27631. while (this.spriteManagers.length) {
  27632. this.spriteManagers[0].dispose();
  27633. }
  27634. // Release postProcesses
  27635. while (this.postProcesses.length) {
  27636. this.postProcesses[0].dispose();
  27637. }
  27638. // Release layers
  27639. while (this.layers.length) {
  27640. this.layers[0].dispose();
  27641. }
  27642. while (this.effectLayers.length) {
  27643. this.effectLayers[0].dispose();
  27644. }
  27645. // Release textures
  27646. while (this.textures.length) {
  27647. this.textures[0].dispose();
  27648. }
  27649. // Release UBO
  27650. this._sceneUbo.dispose();
  27651. if (this._alternateSceneUbo) {
  27652. this._alternateSceneUbo.dispose();
  27653. }
  27654. // Post-processes
  27655. this.postProcessManager.dispose();
  27656. if (this._postProcessRenderPipelineManager) {
  27657. this._postProcessRenderPipelineManager.dispose();
  27658. }
  27659. // Physics
  27660. if (this._physicsEngine) {
  27661. this.disablePhysicsEngine();
  27662. }
  27663. // Remove from engine
  27664. index = this._engine.scenes.indexOf(this);
  27665. if (index > -1) {
  27666. this._engine.scenes.splice(index, 1);
  27667. }
  27668. this._engine.wipeCaches(true);
  27669. this._isDisposed = true;
  27670. };
  27671. Object.defineProperty(Scene.prototype, "isDisposed", {
  27672. /**
  27673. * Gets if the scene is already disposed
  27674. */
  27675. get: function () {
  27676. return this._isDisposed;
  27677. },
  27678. enumerable: true,
  27679. configurable: true
  27680. });
  27681. /**
  27682. * Releases sounds & soundtracks
  27683. */
  27684. Scene.prototype.disposeSounds = function () {
  27685. if (!this._mainSoundTrack) {
  27686. return;
  27687. }
  27688. this.mainSoundTrack.dispose();
  27689. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27690. this.soundTracks[scIndex].dispose();
  27691. }
  27692. };
  27693. // Octrees
  27694. /**
  27695. * Get the world extend vectors with an optional filter
  27696. *
  27697. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27698. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27699. */
  27700. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27701. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27702. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27703. filterPredicate = filterPredicate || (function () { return true; });
  27704. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27705. mesh.computeWorldMatrix(true);
  27706. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27707. return;
  27708. }
  27709. var boundingInfo = mesh.getBoundingInfo();
  27710. var minBox = boundingInfo.boundingBox.minimumWorld;
  27711. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27712. BABYLON.Tools.CheckExtends(minBox, min, max);
  27713. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27714. });
  27715. return {
  27716. min: min,
  27717. max: max
  27718. };
  27719. };
  27720. /**
  27721. * Creates or updates the octree used to boost selection (picking)
  27722. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27723. * @param maxCapacity defines the maximum capacity per leaf
  27724. * @param maxDepth defines the maximum depth of the octree
  27725. * @returns an octree of AbstractMesh
  27726. */
  27727. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27728. if (maxCapacity === void 0) { maxCapacity = 64; }
  27729. if (maxDepth === void 0) { maxDepth = 2; }
  27730. if (!this._selectionOctree) {
  27731. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27732. }
  27733. var worldExtends = this.getWorldExtends();
  27734. // Update octree
  27735. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27736. return this._selectionOctree;
  27737. };
  27738. // Picking
  27739. /**
  27740. * Creates a ray that can be used to pick in the scene
  27741. * @param x defines the x coordinate of the origin (on-screen)
  27742. * @param y defines the y coordinate of the origin (on-screen)
  27743. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27744. * @param camera defines the camera to use for the picking
  27745. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27746. * @returns a Ray
  27747. */
  27748. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27749. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27750. var result = BABYLON.Ray.Zero();
  27751. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27752. return result;
  27753. };
  27754. /**
  27755. * Creates a ray that can be used to pick in the scene
  27756. * @param x defines the x coordinate of the origin (on-screen)
  27757. * @param y defines the y coordinate of the origin (on-screen)
  27758. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27759. * @param result defines the ray where to store the picking ray
  27760. * @param camera defines the camera to use for the picking
  27761. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27762. * @returns the current scene
  27763. */
  27764. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27765. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27766. var engine = this._engine;
  27767. if (!camera) {
  27768. if (!this.activeCamera)
  27769. throw new Error("Active camera not set");
  27770. camera = this.activeCamera;
  27771. }
  27772. var cameraViewport = camera.viewport;
  27773. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27774. // Moving coordinates to local viewport world
  27775. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27776. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27777. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27778. return this;
  27779. };
  27780. /**
  27781. * Creates a ray that can be used to pick in the scene
  27782. * @param x defines the x coordinate of the origin (on-screen)
  27783. * @param y defines the y coordinate of the origin (on-screen)
  27784. * @param camera defines the camera to use for the picking
  27785. * @returns a Ray
  27786. */
  27787. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27788. var result = BABYLON.Ray.Zero();
  27789. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27790. return result;
  27791. };
  27792. /**
  27793. * Creates a ray that can be used to pick in the scene
  27794. * @param x defines the x coordinate of the origin (on-screen)
  27795. * @param y defines the y coordinate of the origin (on-screen)
  27796. * @param result defines the ray where to store the picking ray
  27797. * @param camera defines the camera to use for the picking
  27798. * @returns the current scene
  27799. */
  27800. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27801. if (!BABYLON.PickingInfo) {
  27802. return this;
  27803. }
  27804. var engine = this._engine;
  27805. if (!camera) {
  27806. if (!this.activeCamera)
  27807. throw new Error("Active camera not set");
  27808. camera = this.activeCamera;
  27809. }
  27810. var cameraViewport = camera.viewport;
  27811. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27812. var identity = BABYLON.Matrix.Identity();
  27813. // Moving coordinates to local viewport world
  27814. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27815. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27816. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27817. return this;
  27818. };
  27819. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27820. if (!BABYLON.PickingInfo) {
  27821. return null;
  27822. }
  27823. var pickingInfo = null;
  27824. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27825. var mesh = this.meshes[meshIndex];
  27826. if (predicate) {
  27827. if (!predicate(mesh)) {
  27828. continue;
  27829. }
  27830. }
  27831. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27832. continue;
  27833. }
  27834. var world = mesh.getWorldMatrix();
  27835. var ray = rayFunction(world);
  27836. var result = mesh.intersects(ray, fastCheck);
  27837. if (!result || !result.hit)
  27838. continue;
  27839. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27840. continue;
  27841. pickingInfo = result;
  27842. if (fastCheck) {
  27843. break;
  27844. }
  27845. }
  27846. return pickingInfo || new BABYLON.PickingInfo();
  27847. };
  27848. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27849. if (!BABYLON.PickingInfo) {
  27850. return null;
  27851. }
  27852. var pickingInfos = new Array();
  27853. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27854. var mesh = this.meshes[meshIndex];
  27855. if (predicate) {
  27856. if (!predicate(mesh)) {
  27857. continue;
  27858. }
  27859. }
  27860. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27861. continue;
  27862. }
  27863. var world = mesh.getWorldMatrix();
  27864. var ray = rayFunction(world);
  27865. var result = mesh.intersects(ray, false);
  27866. if (!result || !result.hit)
  27867. continue;
  27868. pickingInfos.push(result);
  27869. }
  27870. return pickingInfos;
  27871. };
  27872. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27873. if (!BABYLON.PickingInfo) {
  27874. return null;
  27875. }
  27876. var pickingInfo = null;
  27877. if (!camera) {
  27878. if (!this.activeCamera) {
  27879. return null;
  27880. }
  27881. camera = this.activeCamera;
  27882. }
  27883. if (this.spriteManagers.length > 0) {
  27884. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  27885. var spriteManager = this.spriteManagers[spriteIndex];
  27886. if (!spriteManager.isPickable) {
  27887. continue;
  27888. }
  27889. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  27890. if (!result || !result.hit)
  27891. continue;
  27892. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27893. continue;
  27894. pickingInfo = result;
  27895. if (fastCheck) {
  27896. break;
  27897. }
  27898. }
  27899. }
  27900. return pickingInfo || new BABYLON.PickingInfo();
  27901. };
  27902. /** Launch a ray to try to pick a mesh in the scene
  27903. * @param x position on screen
  27904. * @param y position on screen
  27905. * @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
  27906. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27907. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27908. * @returns a PickingInfo
  27909. */
  27910. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  27911. var _this = this;
  27912. if (!BABYLON.PickingInfo) {
  27913. return null;
  27914. }
  27915. return this._internalPick(function (world) {
  27916. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  27917. return _this._tempPickingRay;
  27918. }, predicate, fastCheck);
  27919. };
  27920. /** Launch a ray to try to pick a sprite in the scene
  27921. * @param x position on screen
  27922. * @param y position on screen
  27923. * @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
  27924. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  27925. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27926. * @returns a PickingInfo
  27927. */
  27928. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  27929. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  27930. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  27931. };
  27932. /** Use the given ray to pick a mesh in the scene
  27933. * @param ray The ray to use to pick meshes
  27934. * @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
  27935. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  27936. * @returns a PickingInfo
  27937. */
  27938. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  27939. var _this = this;
  27940. return this._internalPick(function (world) {
  27941. if (!_this._pickWithRayInverseMatrix) {
  27942. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27943. }
  27944. world.invertToRef(_this._pickWithRayInverseMatrix);
  27945. if (!_this._cachedRayForTransform) {
  27946. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27947. }
  27948. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27949. return _this._cachedRayForTransform;
  27950. }, predicate, fastCheck);
  27951. };
  27952. /**
  27953. * Launch a ray to try to pick a mesh in the scene
  27954. * @param x X position on screen
  27955. * @param y Y position on screen
  27956. * @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
  27957. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  27958. * @returns an array of PickingInfo
  27959. */
  27960. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  27961. var _this = this;
  27962. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  27963. };
  27964. /**
  27965. * Launch a ray to try to pick a mesh in the scene
  27966. * @param ray Ray to use
  27967. * @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
  27968. * @returns an array of PickingInfo
  27969. */
  27970. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  27971. var _this = this;
  27972. return this._internalMultiPick(function (world) {
  27973. if (!_this._pickWithRayInverseMatrix) {
  27974. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  27975. }
  27976. world.invertToRef(_this._pickWithRayInverseMatrix);
  27977. if (!_this._cachedRayForTransform) {
  27978. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  27979. }
  27980. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  27981. return _this._cachedRayForTransform;
  27982. }, predicate);
  27983. };
  27984. /**
  27985. * Force the value of meshUnderPointer
  27986. * @param mesh defines the mesh to use
  27987. */
  27988. Scene.prototype.setPointerOverMesh = function (mesh) {
  27989. if (this._pointerOverMesh === mesh) {
  27990. return;
  27991. }
  27992. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27993. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27994. }
  27995. this._pointerOverMesh = mesh;
  27996. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  27997. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  27998. }
  27999. };
  28000. /**
  28001. * Gets the mesh under the pointer
  28002. * @returns a Mesh or null if no mesh is under the pointer
  28003. */
  28004. Scene.prototype.getPointerOverMesh = function () {
  28005. return this._pointerOverMesh;
  28006. };
  28007. /**
  28008. * Force the sprite under the pointer
  28009. * @param sprite defines the sprite to use
  28010. */
  28011. Scene.prototype.setPointerOverSprite = function (sprite) {
  28012. if (this._pointerOverSprite === sprite) {
  28013. return;
  28014. }
  28015. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28016. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28017. }
  28018. this._pointerOverSprite = sprite;
  28019. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28020. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28021. }
  28022. };
  28023. /**
  28024. * Gets the sprite under the pointer
  28025. * @returns a Sprite or null if no sprite is under the pointer
  28026. */
  28027. Scene.prototype.getPointerOverSprite = function () {
  28028. return this._pointerOverSprite;
  28029. };
  28030. // Physics
  28031. /**
  28032. * Gets the current physics engine
  28033. * @returns a PhysicsEngine or null if none attached
  28034. */
  28035. Scene.prototype.getPhysicsEngine = function () {
  28036. return this._physicsEngine;
  28037. };
  28038. /**
  28039. * Enables physics to the current scene
  28040. * @param gravity defines the scene's gravity for the physics engine
  28041. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28042. * @return a boolean indicating if the physics engine was initialized
  28043. */
  28044. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28045. if (gravity === void 0) { gravity = null; }
  28046. if (this._physicsEngine) {
  28047. return true;
  28048. }
  28049. try {
  28050. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28051. return true;
  28052. }
  28053. catch (e) {
  28054. BABYLON.Tools.Error(e.message);
  28055. return false;
  28056. }
  28057. };
  28058. /**
  28059. * Disables and disposes the physics engine associated with the scene
  28060. */
  28061. Scene.prototype.disablePhysicsEngine = function () {
  28062. if (!this._physicsEngine) {
  28063. return;
  28064. }
  28065. this._physicsEngine.dispose();
  28066. this._physicsEngine = null;
  28067. };
  28068. /**
  28069. * Gets a boolean indicating if there is an active physics engine
  28070. * @returns a boolean indicating if there is an active physics engine
  28071. */
  28072. Scene.prototype.isPhysicsEnabled = function () {
  28073. return this._physicsEngine !== undefined;
  28074. };
  28075. /**
  28076. * Deletes a physics compound impostor
  28077. * @param compound defines the compound to delete
  28078. */
  28079. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28080. var mesh = compound.parts[0].mesh;
  28081. if (mesh.physicsImpostor) {
  28082. mesh.physicsImpostor.dispose( /*true*/);
  28083. mesh.physicsImpostor = null;
  28084. }
  28085. };
  28086. // Misc.
  28087. /** @ignore */
  28088. Scene.prototype._rebuildGeometries = function () {
  28089. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28090. var geometry = _a[_i];
  28091. geometry._rebuild();
  28092. }
  28093. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28094. var mesh = _c[_b];
  28095. mesh._rebuild();
  28096. }
  28097. if (this.postProcessManager) {
  28098. this.postProcessManager._rebuild();
  28099. }
  28100. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28101. var layer = _e[_d];
  28102. layer._rebuild();
  28103. }
  28104. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28105. var effectLayer = _g[_f];
  28106. effectLayer._rebuild();
  28107. }
  28108. if (this._boundingBoxRenderer) {
  28109. this._boundingBoxRenderer._rebuild();
  28110. }
  28111. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28112. var system = _j[_h];
  28113. system.rebuild();
  28114. }
  28115. if (this._postProcessRenderPipelineManager) {
  28116. this._postProcessRenderPipelineManager._rebuild();
  28117. }
  28118. };
  28119. /** @ignore */
  28120. Scene.prototype._rebuildTextures = function () {
  28121. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28122. var texture = _a[_i];
  28123. texture._rebuild();
  28124. }
  28125. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28126. };
  28127. /**
  28128. * Creates a default light for the scene.
  28129. * @param replace Whether to replace the existing lights in the scene.
  28130. */
  28131. Scene.prototype.createDefaultLight = function (replace) {
  28132. if (replace === void 0) { replace = false; }
  28133. // Dispose existing light in replace mode.
  28134. if (replace) {
  28135. if (this.lights) {
  28136. for (var i = 0; i < this.lights.length; i++) {
  28137. this.lights[i].dispose();
  28138. }
  28139. }
  28140. }
  28141. // Light
  28142. if (this.lights.length === 0) {
  28143. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28144. }
  28145. };
  28146. /**
  28147. * Creates a default camera for the scene.
  28148. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28149. * @param replace Whether to replace the existing active camera in the scene.
  28150. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28151. */
  28152. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28153. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28154. if (replace === void 0) { replace = false; }
  28155. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28156. // Dispose existing camera in replace mode.
  28157. if (replace) {
  28158. if (this.activeCamera) {
  28159. this.activeCamera.dispose();
  28160. this.activeCamera = null;
  28161. }
  28162. }
  28163. // Camera
  28164. if (!this.activeCamera) {
  28165. var worldExtends = this.getWorldExtends();
  28166. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28167. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28168. var camera;
  28169. var radius = worldSize.length() * 1.5;
  28170. // empty scene scenario!
  28171. if (!isFinite(radius)) {
  28172. radius = 1;
  28173. worldCenter.copyFromFloats(0, 0, 0);
  28174. }
  28175. if (createArcRotateCamera) {
  28176. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28177. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28178. arcRotateCamera.wheelPrecision = 100 / radius;
  28179. camera = arcRotateCamera;
  28180. }
  28181. else {
  28182. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28183. freeCamera.setTarget(worldCenter);
  28184. camera = freeCamera;
  28185. }
  28186. camera.minZ = radius * 0.01;
  28187. camera.maxZ = radius * 1000;
  28188. camera.speed = radius * 0.2;
  28189. this.activeCamera = camera;
  28190. var canvas = this.getEngine().getRenderingCanvas();
  28191. if (attachCameraControls && canvas) {
  28192. camera.attachControl(canvas);
  28193. }
  28194. }
  28195. };
  28196. /**
  28197. * Creates a default camera and a default light
  28198. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28199. * @param replace defines if the camera and/or light will replace the existing ones
  28200. * @param attachCameraControls defines if attachControl will be called on the new camera
  28201. */
  28202. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28203. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28204. if (replace === void 0) { replace = false; }
  28205. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28206. this.createDefaultLight(replace);
  28207. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28208. };
  28209. /**
  28210. * Creates a new sky box
  28211. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28212. * @param environmentTexture defines the texture to use as environment texture
  28213. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28214. * @param scale defines the overall scale of the skybox
  28215. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28216. * @returns a new mesh holding the sky box
  28217. */
  28218. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28219. if (pbr === void 0) { pbr = false; }
  28220. if (scale === void 0) { scale = 1000; }
  28221. if (blur === void 0) { blur = 0; }
  28222. if (environmentTexture) {
  28223. this.environmentTexture = environmentTexture;
  28224. }
  28225. if (!this.environmentTexture) {
  28226. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28227. return null;
  28228. }
  28229. // Skybox
  28230. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28231. if (pbr) {
  28232. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28233. hdrSkyboxMaterial.backFaceCulling = false;
  28234. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28235. if (hdrSkyboxMaterial.reflectionTexture) {
  28236. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28237. }
  28238. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28239. hdrSkyboxMaterial.disableLighting = true;
  28240. hdrSkyboxMaterial.twoSidedLighting = true;
  28241. hdrSkybox.infiniteDistance = true;
  28242. hdrSkybox.material = hdrSkyboxMaterial;
  28243. }
  28244. else {
  28245. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28246. skyboxMaterial.backFaceCulling = false;
  28247. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28248. if (skyboxMaterial.reflectionTexture) {
  28249. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28250. }
  28251. skyboxMaterial.disableLighting = true;
  28252. hdrSkybox.infiniteDistance = true;
  28253. hdrSkybox.material = skyboxMaterial;
  28254. }
  28255. return hdrSkybox;
  28256. };
  28257. /**
  28258. * Creates a new environment
  28259. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28260. * @param options defines the options you can use to configure the environment
  28261. * @returns the new EnvironmentHelper
  28262. */
  28263. Scene.prototype.createDefaultEnvironment = function (options) {
  28264. if (BABYLON.EnvironmentHelper) {
  28265. return new BABYLON.EnvironmentHelper(options, this);
  28266. }
  28267. return null;
  28268. };
  28269. /**
  28270. * Creates a new VREXperienceHelper
  28271. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28272. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28273. * @returns a new VREXperienceHelper
  28274. */
  28275. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28276. if (webVROptions === void 0) { webVROptions = {}; }
  28277. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28278. };
  28279. // Tags
  28280. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28281. if (tagsQuery === undefined) {
  28282. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28283. return list;
  28284. }
  28285. var listByTags = [];
  28286. forEach = forEach || (function (item) { return; });
  28287. for (var i in list) {
  28288. var item = list[i];
  28289. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28290. listByTags.push(item);
  28291. forEach(item);
  28292. }
  28293. }
  28294. return listByTags;
  28295. };
  28296. /**
  28297. * Get a list of meshes by tags
  28298. * @param tagsQuery defines the tags query to use
  28299. * @param forEach defines a predicate used to filter results
  28300. * @returns an array of Mesh
  28301. */
  28302. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28303. return this._getByTags(this.meshes, tagsQuery, forEach);
  28304. };
  28305. /**
  28306. * Get a list of cameras by tags
  28307. * @param tagsQuery defines the tags query to use
  28308. * @param forEach defines a predicate used to filter results
  28309. * @returns an array of Camera
  28310. */
  28311. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28312. return this._getByTags(this.cameras, tagsQuery, forEach);
  28313. };
  28314. /**
  28315. * Get a list of lights by tags
  28316. * @param tagsQuery defines the tags query to use
  28317. * @param forEach defines a predicate used to filter results
  28318. * @returns an array of Light
  28319. */
  28320. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28321. return this._getByTags(this.lights, tagsQuery, forEach);
  28322. };
  28323. /**
  28324. * Get a list of materials by tags
  28325. * @param tagsQuery defines the tags query to use
  28326. * @param forEach defines a predicate used to filter results
  28327. * @returns an array of Material
  28328. */
  28329. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28330. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28331. };
  28332. /**
  28333. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28334. * This allowed control for front to back rendering or reversly depending of the special needs.
  28335. *
  28336. * @param renderingGroupId The rendering group id corresponding to its index
  28337. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28338. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28339. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28340. */
  28341. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28342. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28343. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28344. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28345. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28346. };
  28347. /**
  28348. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28349. *
  28350. * @param renderingGroupId The rendering group id corresponding to its index
  28351. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28352. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28353. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28354. */
  28355. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28356. if (depth === void 0) { depth = true; }
  28357. if (stencil === void 0) { stencil = true; }
  28358. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28359. };
  28360. /**
  28361. * Will flag all materials as dirty to trigger new shader compilation
  28362. * @param flag defines the flag used to specify which material part must be marked as dirty
  28363. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28364. */
  28365. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28366. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28367. var material = _a[_i];
  28368. if (predicate && !predicate(material)) {
  28369. continue;
  28370. }
  28371. material.markAsDirty(flag);
  28372. }
  28373. };
  28374. /** @ignore */
  28375. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28376. var _this = this;
  28377. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28378. this._activeRequests.push(request);
  28379. request.onCompleteObservable.add(function (request) {
  28380. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28381. });
  28382. return request;
  28383. };
  28384. /** @ignore */
  28385. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28386. var _this = this;
  28387. return new Promise(function (resolve, reject) {
  28388. _this._loadFile(url, function (data) {
  28389. resolve(data);
  28390. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28391. reject(exception);
  28392. });
  28393. });
  28394. };
  28395. // Statics
  28396. Scene._FOGMODE_NONE = 0;
  28397. Scene._FOGMODE_EXP = 1;
  28398. Scene._FOGMODE_EXP2 = 2;
  28399. Scene._FOGMODE_LINEAR = 3;
  28400. Scene._uniqueIdCounter = 0;
  28401. /**
  28402. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28403. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28404. */
  28405. Scene.MinDeltaTime = 1.0;
  28406. /**
  28407. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28408. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28409. */
  28410. Scene.MaxDeltaTime = 1000.0;
  28411. /** The distance in pixel that you have to move to prevent some events */
  28412. Scene.DragMovementThreshold = 10; // in pixels
  28413. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28414. Scene.LongPressDelay = 500; // in milliseconds
  28415. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28416. Scene.DoubleClickDelay = 300; // in milliseconds
  28417. /** If you need to check double click without raising a single click at first click, enable this flag */
  28418. Scene.ExclusiveDoubleClickMode = false;
  28419. return Scene;
  28420. }());
  28421. BABYLON.Scene = Scene;
  28422. })(BABYLON || (BABYLON = {}));
  28423. //# sourceMappingURL=babylon.scene.js.map
  28424. var BABYLON;
  28425. (function (BABYLON) {
  28426. /**
  28427. * Set of assets to keep when moving a scene into an asset container.
  28428. */
  28429. var KeepAssets = /** @class */ (function () {
  28430. function KeepAssets() {
  28431. /**
  28432. * Cameras to keep.
  28433. */
  28434. this.cameras = new Array();
  28435. /**
  28436. * Lights to keep.
  28437. */
  28438. this.lights = new Array();
  28439. /**
  28440. * Meshes to keep.
  28441. */
  28442. this.meshes = new Array();
  28443. /**
  28444. * Skeletons to keep.
  28445. */
  28446. this.skeletons = new Array();
  28447. /**
  28448. * ParticleSystems to keep.
  28449. */
  28450. this.particleSystems = new Array();
  28451. /**
  28452. * Animations to keep.
  28453. */
  28454. this.animations = new Array();
  28455. /**
  28456. * AnimationGroups to keep.
  28457. */
  28458. this.animationGroups = new Array();
  28459. /**
  28460. * MultiMaterials to keep.
  28461. */
  28462. this.multiMaterials = new Array();
  28463. /**
  28464. * Materials to keep.
  28465. */
  28466. this.materials = new Array();
  28467. /**
  28468. * MorphTargetManagers to keep.
  28469. */
  28470. this.morphTargetManagers = new Array();
  28471. /**
  28472. * Geometries to keep.
  28473. */
  28474. this.geometries = new Array();
  28475. /**
  28476. * TransformNodes to keep.
  28477. */
  28478. this.transformNodes = new Array();
  28479. /**
  28480. * LensFlareSystems to keep.
  28481. */
  28482. this.lensFlareSystems = new Array();
  28483. /**
  28484. * ShadowGenerators to keep.
  28485. */
  28486. this.shadowGenerators = new Array();
  28487. /**
  28488. * ActionManagers to keep.
  28489. */
  28490. this.actionManagers = new Array();
  28491. /**
  28492. * Sounds to keep.
  28493. */
  28494. this.sounds = new Array();
  28495. /**
  28496. * Textures to keep.
  28497. */
  28498. this.textures = new Array();
  28499. /**
  28500. * Effect layers to keep.
  28501. */
  28502. this.effectLayers = new Array();
  28503. }
  28504. return KeepAssets;
  28505. }());
  28506. BABYLON.KeepAssets = KeepAssets;
  28507. /**
  28508. * Container with a set of assets that can be added or removed from a scene.
  28509. */
  28510. var AssetContainer = /** @class */ (function () {
  28511. /**
  28512. * Instantiates an AssetContainer.
  28513. * @param scene The scene the AssetContainer belongs to.
  28514. */
  28515. function AssetContainer(scene) {
  28516. // Objects
  28517. /**
  28518. * Cameras populated in the container.
  28519. */
  28520. this.cameras = new Array();
  28521. /**
  28522. * Lights populated in the container.
  28523. */
  28524. this.lights = new Array();
  28525. /**
  28526. * Meshes populated in the container.
  28527. */
  28528. this.meshes = new Array();
  28529. /**
  28530. * Skeletons populated in the container.
  28531. */
  28532. this.skeletons = new Array();
  28533. /**
  28534. * ParticleSystems populated in the container.
  28535. */
  28536. this.particleSystems = new Array();
  28537. /**
  28538. * Animations populated in the container.
  28539. */
  28540. this.animations = new Array();
  28541. /**
  28542. * AnimationGroups populated in the container.
  28543. */
  28544. this.animationGroups = new Array();
  28545. /**
  28546. * MultiMaterials populated in the container.
  28547. */
  28548. this.multiMaterials = new Array();
  28549. /**
  28550. * Materials populated in the container.
  28551. */
  28552. this.materials = new Array();
  28553. /**
  28554. * MorphTargetManagers populated in the container.
  28555. */
  28556. this.morphTargetManagers = new Array();
  28557. /**
  28558. * Geometries populated in the container.
  28559. */
  28560. this.geometries = new Array();
  28561. /**
  28562. * TransformNodes populated in the container.
  28563. */
  28564. this.transformNodes = new Array();
  28565. /**
  28566. * LensFlareSystems populated in the container.
  28567. */
  28568. this.lensFlareSystems = new Array();
  28569. /**
  28570. * ShadowGenerators populated in the container.
  28571. */
  28572. this.shadowGenerators = new Array();
  28573. /**
  28574. * ActionManagers populated in the container.
  28575. */
  28576. this.actionManagers = new Array();
  28577. /**
  28578. * Sounds populated in the container.
  28579. */
  28580. this.sounds = new Array();
  28581. /**
  28582. * Textures populated in the container.
  28583. */
  28584. this.textures = new Array();
  28585. /**
  28586. * Effect layers populated in the container.
  28587. */
  28588. this.effectLayers = new Array();
  28589. this.scene = scene;
  28590. }
  28591. /**
  28592. * Adds all the assets from the container to the scene.
  28593. */
  28594. AssetContainer.prototype.addAllToScene = function () {
  28595. var _this = this;
  28596. this.cameras.forEach(function (o) {
  28597. _this.scene.addCamera(o);
  28598. });
  28599. this.lights.forEach(function (o) {
  28600. _this.scene.addLight(o);
  28601. });
  28602. this.meshes.forEach(function (o) {
  28603. _this.scene.addMesh(o);
  28604. });
  28605. this.skeletons.forEach(function (o) {
  28606. _this.scene.addSkeleton(o);
  28607. });
  28608. this.particleSystems.forEach(function (o) {
  28609. _this.scene.addParticleSystem(o);
  28610. });
  28611. this.animations.forEach(function (o) {
  28612. _this.scene.addAnimation(o);
  28613. });
  28614. this.animationGroups.forEach(function (o) {
  28615. _this.scene.addAnimationGroup(o);
  28616. });
  28617. this.multiMaterials.forEach(function (o) {
  28618. _this.scene.addMultiMaterial(o);
  28619. });
  28620. this.materials.forEach(function (o) {
  28621. _this.scene.addMaterial(o);
  28622. });
  28623. this.morphTargetManagers.forEach(function (o) {
  28624. _this.scene.addMorphTargetManager(o);
  28625. });
  28626. this.geometries.forEach(function (o) {
  28627. _this.scene.addGeometry(o);
  28628. });
  28629. this.transformNodes.forEach(function (o) {
  28630. _this.scene.addTransformNode(o);
  28631. });
  28632. this.lensFlareSystems.forEach(function (o) {
  28633. _this.scene.addLensFlareSystem(o);
  28634. });
  28635. this.actionManagers.forEach(function (o) {
  28636. _this.scene.addActionManager(o);
  28637. });
  28638. this.sounds.forEach(function (o) {
  28639. o.play();
  28640. o.autoplay = true;
  28641. _this.scene.mainSoundTrack.AddSound(o);
  28642. });
  28643. this.textures.forEach(function (o) {
  28644. _this.scene.addTexture(o);
  28645. });
  28646. this.effectLayers.forEach(function (o) {
  28647. _this.scene.addEffectLayer(o);
  28648. });
  28649. };
  28650. /**
  28651. * Removes all the assets in the container from the scene
  28652. */
  28653. AssetContainer.prototype.removeAllFromScene = function () {
  28654. var _this = this;
  28655. this.cameras.forEach(function (o) {
  28656. _this.scene.removeCamera(o);
  28657. });
  28658. this.lights.forEach(function (o) {
  28659. _this.scene.removeLight(o);
  28660. });
  28661. this.meshes.forEach(function (o) {
  28662. _this.scene.removeMesh(o);
  28663. });
  28664. this.skeletons.forEach(function (o) {
  28665. _this.scene.removeSkeleton(o);
  28666. });
  28667. this.particleSystems.forEach(function (o) {
  28668. _this.scene.removeParticleSystem(o);
  28669. });
  28670. this.animations.forEach(function (o) {
  28671. _this.scene.removeAnimation(o);
  28672. });
  28673. this.animationGroups.forEach(function (o) {
  28674. _this.scene.removeAnimationGroup(o);
  28675. });
  28676. this.multiMaterials.forEach(function (o) {
  28677. _this.scene.removeMultiMaterial(o);
  28678. });
  28679. this.materials.forEach(function (o) {
  28680. _this.scene.removeMaterial(o);
  28681. });
  28682. this.morphTargetManagers.forEach(function (o) {
  28683. _this.scene.removeMorphTargetManager(o);
  28684. });
  28685. this.geometries.forEach(function (o) {
  28686. _this.scene.removeGeometry(o);
  28687. });
  28688. this.transformNodes.forEach(function (o) {
  28689. _this.scene.removeTransformNode(o);
  28690. });
  28691. this.lensFlareSystems.forEach(function (o) {
  28692. _this.scene.removeLensFlareSystem(o);
  28693. });
  28694. this.actionManagers.forEach(function (o) {
  28695. _this.scene.removeActionManager(o);
  28696. });
  28697. this.sounds.forEach(function (o) {
  28698. o.stop();
  28699. o.autoplay = false;
  28700. _this.scene.mainSoundTrack.RemoveSound(o);
  28701. });
  28702. this.textures.forEach(function (o) {
  28703. _this.scene.removeTexture(o);
  28704. });
  28705. this.effectLayers.forEach(function (o) {
  28706. _this.scene.removeEffectLayer(o);
  28707. });
  28708. };
  28709. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28710. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28711. var asset = sourceAssets_1[_i];
  28712. var move = true;
  28713. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28714. var keepAsset = keepAssets_1[_a];
  28715. if (asset === keepAsset) {
  28716. move = false;
  28717. break;
  28718. }
  28719. }
  28720. if (move) {
  28721. targetAssets.push(asset);
  28722. }
  28723. }
  28724. };
  28725. /**
  28726. * Removes all the assets contained in the scene and adds them to the container.
  28727. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28728. */
  28729. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28730. if (keepAssets === undefined) {
  28731. keepAssets = new KeepAssets();
  28732. }
  28733. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28734. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28735. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28736. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28737. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28738. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28739. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28740. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28741. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28742. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28743. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28744. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28745. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28746. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28747. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28748. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28749. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28750. this.removeAllFromScene();
  28751. };
  28752. return AssetContainer;
  28753. }());
  28754. BABYLON.AssetContainer = AssetContainer;
  28755. })(BABYLON || (BABYLON = {}));
  28756. //# sourceMappingURL=babylon.assetContainer.js.map
  28757. var BABYLON;
  28758. (function (BABYLON) {
  28759. var Buffer = /** @class */ (function () {
  28760. /**
  28761. * Constructor
  28762. * @param engine the engine
  28763. * @param data the data to use for this buffer
  28764. * @param updatable whether the data is updatable
  28765. * @param stride the stride (optional)
  28766. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28767. * @param instanced whether the buffer is instanced (optional)
  28768. * @param useBytes set to true if the stride in in bytes (optional)
  28769. */
  28770. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28771. if (stride === void 0) { stride = 0; }
  28772. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28773. if (instanced === void 0) { instanced = false; }
  28774. if (useBytes === void 0) { useBytes = false; }
  28775. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28776. this._engine = engine.getScene().getEngine();
  28777. }
  28778. else {
  28779. this._engine = engine;
  28780. }
  28781. this._updatable = updatable;
  28782. this._instanced = instanced;
  28783. this._data = data;
  28784. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28785. if (!postponeInternalCreation) { // by default
  28786. this.create();
  28787. }
  28788. }
  28789. /**
  28790. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28791. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28792. * @param offset defines offset in the buffer (0 by default)
  28793. * @param size defines the size in floats of attributes (position is 3 for instance)
  28794. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28795. * @param instanced defines if the vertex buffer contains indexed data
  28796. * @param useBytes defines if the offset and stride are in bytes
  28797. * @returns the new vertex buffer
  28798. */
  28799. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28800. if (useBytes === void 0) { useBytes = false; }
  28801. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28802. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28803. // a lot of these parameters are ignored as they are overriden by the buffer
  28804. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28805. };
  28806. // Properties
  28807. Buffer.prototype.isUpdatable = function () {
  28808. return this._updatable;
  28809. };
  28810. Buffer.prototype.getData = function () {
  28811. return this._data;
  28812. };
  28813. Buffer.prototype.getBuffer = function () {
  28814. return this._buffer;
  28815. };
  28816. /**
  28817. * Gets the stride in float32 units (i.e. byte stride / 4).
  28818. * May not be an integer if the byte stride is not divisible by 4.
  28819. * DEPRECATED. Use byteStride instead.
  28820. * @returns the stride in float32 units
  28821. */
  28822. Buffer.prototype.getStrideSize = function () {
  28823. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28824. };
  28825. // Methods
  28826. Buffer.prototype.create = function (data) {
  28827. if (data === void 0) { data = null; }
  28828. if (!data && this._buffer) {
  28829. return; // nothing to do
  28830. }
  28831. data = data || this._data;
  28832. if (!data) {
  28833. return;
  28834. }
  28835. if (!this._buffer) { // create buffer
  28836. if (this._updatable) {
  28837. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28838. this._data = data;
  28839. }
  28840. else {
  28841. this._buffer = this._engine.createVertexBuffer(data);
  28842. }
  28843. }
  28844. else if (this._updatable) { // update buffer
  28845. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28846. this._data = data;
  28847. }
  28848. };
  28849. Buffer.prototype._rebuild = function () {
  28850. this._buffer = null;
  28851. this.create(this._data);
  28852. };
  28853. Buffer.prototype.update = function (data) {
  28854. this.create(data);
  28855. };
  28856. /**
  28857. * Updates the data directly.
  28858. * @param data the new data
  28859. * @param offset the new offset
  28860. * @param vertexCount the vertex count (optional)
  28861. * @param useBytes set to true if the offset is in bytes
  28862. */
  28863. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28864. if (useBytes === void 0) { useBytes = false; }
  28865. if (!this._buffer) {
  28866. return;
  28867. }
  28868. if (this._updatable) { // update buffer
  28869. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28870. this._data = null;
  28871. }
  28872. };
  28873. Buffer.prototype.dispose = function () {
  28874. if (!this._buffer) {
  28875. return;
  28876. }
  28877. if (this._engine._releaseBuffer(this._buffer)) {
  28878. this._buffer = null;
  28879. }
  28880. };
  28881. return Buffer;
  28882. }());
  28883. BABYLON.Buffer = Buffer;
  28884. })(BABYLON || (BABYLON = {}));
  28885. //# sourceMappingURL=babylon.buffer.js.map
  28886. var BABYLON;
  28887. (function (BABYLON) {
  28888. var VertexBuffer = /** @class */ (function () {
  28889. /**
  28890. * Constructor
  28891. * @param engine the engine
  28892. * @param data the data to use for this vertex buffer
  28893. * @param kind the vertex buffer kind
  28894. * @param updatable whether the data is updatable
  28895. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28896. * @param stride the stride (optional)
  28897. * @param instanced whether the buffer is instanced (optional)
  28898. * @param offset the offset of the data (optional)
  28899. * @param size the number of components (optional)
  28900. * @param type the type of the component (optional)
  28901. * @param normalized whether the data contains normalized data (optional)
  28902. * @param useBytes set to true if stride and offset are in bytes (optional)
  28903. */
  28904. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  28905. if (normalized === void 0) { normalized = false; }
  28906. if (useBytes === void 0) { useBytes = false; }
  28907. if (data instanceof BABYLON.Buffer) {
  28908. this._buffer = data;
  28909. this._ownsBuffer = false;
  28910. }
  28911. else {
  28912. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  28913. this._ownsBuffer = true;
  28914. }
  28915. this._kind = kind;
  28916. if (type == undefined) {
  28917. var data_1 = this.getData();
  28918. this.type = VertexBuffer.FLOAT;
  28919. if (data_1 instanceof Int8Array)
  28920. this.type = VertexBuffer.BYTE;
  28921. else if (data_1 instanceof Uint8Array)
  28922. this.type = VertexBuffer.UNSIGNED_BYTE;
  28923. else if (data_1 instanceof Int16Array)
  28924. this.type = VertexBuffer.SHORT;
  28925. else if (data_1 instanceof Uint16Array)
  28926. this.type = VertexBuffer.UNSIGNED_SHORT;
  28927. else if (data_1 instanceof Int32Array)
  28928. this.type = VertexBuffer.INT;
  28929. else if (data_1 instanceof Uint32Array)
  28930. this.type = VertexBuffer.UNSIGNED_INT;
  28931. }
  28932. else {
  28933. this.type = type;
  28934. }
  28935. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  28936. if (useBytes) {
  28937. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  28938. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  28939. this.byteOffset = offset || 0;
  28940. }
  28941. else {
  28942. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  28943. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  28944. this.byteOffset = (offset || 0) * typeByteLength;
  28945. }
  28946. this.normalized = normalized;
  28947. this._instanced = instanced !== undefined ? instanced : false;
  28948. this._instanceDivisor = instanced ? 1 : 0;
  28949. }
  28950. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  28951. /**
  28952. * Gets or sets the instance divisor when in instanced mode
  28953. */
  28954. get: function () {
  28955. return this._instanceDivisor;
  28956. },
  28957. set: function (value) {
  28958. this._instanceDivisor = value;
  28959. if (value == 0) {
  28960. this._instanced = false;
  28961. }
  28962. else {
  28963. this._instanced = true;
  28964. }
  28965. },
  28966. enumerable: true,
  28967. configurable: true
  28968. });
  28969. VertexBuffer.prototype._rebuild = function () {
  28970. if (!this._buffer) {
  28971. return;
  28972. }
  28973. this._buffer._rebuild();
  28974. };
  28975. /**
  28976. * Returns the kind of the VertexBuffer (string).
  28977. */
  28978. VertexBuffer.prototype.getKind = function () {
  28979. return this._kind;
  28980. };
  28981. // Properties
  28982. /**
  28983. * Boolean : is the VertexBuffer updatable ?
  28984. */
  28985. VertexBuffer.prototype.isUpdatable = function () {
  28986. return this._buffer.isUpdatable();
  28987. };
  28988. /**
  28989. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  28990. */
  28991. VertexBuffer.prototype.getData = function () {
  28992. return this._buffer.getData();
  28993. };
  28994. /**
  28995. * Returns the WebGLBuffer associated to the VertexBuffer.
  28996. */
  28997. VertexBuffer.prototype.getBuffer = function () {
  28998. return this._buffer.getBuffer();
  28999. };
  29000. /**
  29001. * Returns the stride as a multiple of the type byte length.
  29002. * DEPRECATED. Use byteStride instead.
  29003. */
  29004. VertexBuffer.prototype.getStrideSize = function () {
  29005. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29006. };
  29007. /**
  29008. * Returns the offset as a multiple of the type byte length.
  29009. * DEPRECATED. Use byteOffset instead.
  29010. */
  29011. VertexBuffer.prototype.getOffset = function () {
  29012. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29013. };
  29014. /**
  29015. * Returns the number of components per vertex attribute (integer).
  29016. */
  29017. VertexBuffer.prototype.getSize = function () {
  29018. return this._size;
  29019. };
  29020. /**
  29021. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29022. */
  29023. VertexBuffer.prototype.getIsInstanced = function () {
  29024. return this._instanced;
  29025. };
  29026. /**
  29027. * Returns the instancing divisor, zero for non-instanced (integer).
  29028. */
  29029. VertexBuffer.prototype.getInstanceDivisor = function () {
  29030. return this._instanceDivisor;
  29031. };
  29032. // Methods
  29033. /**
  29034. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29035. * Returns the created WebGLBuffer.
  29036. */
  29037. VertexBuffer.prototype.create = function (data) {
  29038. return this._buffer.create(data);
  29039. };
  29040. /**
  29041. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29042. * This function will create a new buffer if the current one is not updatable
  29043. * Returns the updated WebGLBuffer.
  29044. */
  29045. VertexBuffer.prototype.update = function (data) {
  29046. return this._buffer.update(data);
  29047. };
  29048. /**
  29049. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29050. * Returns the directly updated WebGLBuffer.
  29051. * @param data the new data
  29052. * @param offset the new offset
  29053. * @param useBytes set to true if the offset is in bytes
  29054. */
  29055. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29056. if (useBytes === void 0) { useBytes = false; }
  29057. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29058. };
  29059. /**
  29060. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29061. */
  29062. VertexBuffer.prototype.dispose = function () {
  29063. if (this._ownsBuffer) {
  29064. this._buffer.dispose();
  29065. }
  29066. };
  29067. /**
  29068. * Enumerates each value of this vertex buffer as numbers.
  29069. * @param count the number of values to enumerate
  29070. * @param callback the callback function called for each value
  29071. */
  29072. VertexBuffer.prototype.forEach = function (count, callback) {
  29073. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29074. };
  29075. Object.defineProperty(VertexBuffer, "PositionKind", {
  29076. get: function () {
  29077. return VertexBuffer._PositionKind;
  29078. },
  29079. enumerable: true,
  29080. configurable: true
  29081. });
  29082. Object.defineProperty(VertexBuffer, "NormalKind", {
  29083. get: function () {
  29084. return VertexBuffer._NormalKind;
  29085. },
  29086. enumerable: true,
  29087. configurable: true
  29088. });
  29089. Object.defineProperty(VertexBuffer, "TangentKind", {
  29090. get: function () {
  29091. return VertexBuffer._TangentKind;
  29092. },
  29093. enumerable: true,
  29094. configurable: true
  29095. });
  29096. Object.defineProperty(VertexBuffer, "UVKind", {
  29097. get: function () {
  29098. return VertexBuffer._UVKind;
  29099. },
  29100. enumerable: true,
  29101. configurable: true
  29102. });
  29103. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29104. get: function () {
  29105. return VertexBuffer._UV2Kind;
  29106. },
  29107. enumerable: true,
  29108. configurable: true
  29109. });
  29110. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29111. get: function () {
  29112. return VertexBuffer._UV3Kind;
  29113. },
  29114. enumerable: true,
  29115. configurable: true
  29116. });
  29117. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29118. get: function () {
  29119. return VertexBuffer._UV4Kind;
  29120. },
  29121. enumerable: true,
  29122. configurable: true
  29123. });
  29124. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29125. get: function () {
  29126. return VertexBuffer._UV5Kind;
  29127. },
  29128. enumerable: true,
  29129. configurable: true
  29130. });
  29131. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29132. get: function () {
  29133. return VertexBuffer._UV6Kind;
  29134. },
  29135. enumerable: true,
  29136. configurable: true
  29137. });
  29138. Object.defineProperty(VertexBuffer, "ColorKind", {
  29139. get: function () {
  29140. return VertexBuffer._ColorKind;
  29141. },
  29142. enumerable: true,
  29143. configurable: true
  29144. });
  29145. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29146. get: function () {
  29147. return VertexBuffer._MatricesIndicesKind;
  29148. },
  29149. enumerable: true,
  29150. configurable: true
  29151. });
  29152. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29153. get: function () {
  29154. return VertexBuffer._MatricesWeightsKind;
  29155. },
  29156. enumerable: true,
  29157. configurable: true
  29158. });
  29159. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29160. get: function () {
  29161. return VertexBuffer._MatricesIndicesExtraKind;
  29162. },
  29163. enumerable: true,
  29164. configurable: true
  29165. });
  29166. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29167. get: function () {
  29168. return VertexBuffer._MatricesWeightsExtraKind;
  29169. },
  29170. enumerable: true,
  29171. configurable: true
  29172. });
  29173. /**
  29174. * Deduces the stride given a kind.
  29175. * @param kind The kind string to deduce
  29176. * @returns The deduced stride
  29177. */
  29178. VertexBuffer.DeduceStride = function (kind) {
  29179. switch (kind) {
  29180. case VertexBuffer.UVKind:
  29181. case VertexBuffer.UV2Kind:
  29182. case VertexBuffer.UV3Kind:
  29183. case VertexBuffer.UV4Kind:
  29184. case VertexBuffer.UV5Kind:
  29185. case VertexBuffer.UV6Kind:
  29186. return 2;
  29187. case VertexBuffer.NormalKind:
  29188. case VertexBuffer.PositionKind:
  29189. return 3;
  29190. case VertexBuffer.ColorKind:
  29191. case VertexBuffer.MatricesIndicesKind:
  29192. case VertexBuffer.MatricesIndicesExtraKind:
  29193. case VertexBuffer.MatricesWeightsKind:
  29194. case VertexBuffer.MatricesWeightsExtraKind:
  29195. case VertexBuffer.TangentKind:
  29196. return 4;
  29197. default:
  29198. throw new Error("Invalid kind '" + kind + "'");
  29199. }
  29200. };
  29201. /**
  29202. * Gets the byte length of the given type.
  29203. * @param type the type
  29204. * @returns the number of bytes
  29205. */
  29206. VertexBuffer.GetTypeByteLength = function (type) {
  29207. switch (type) {
  29208. case VertexBuffer.BYTE:
  29209. case VertexBuffer.UNSIGNED_BYTE:
  29210. return 1;
  29211. case VertexBuffer.SHORT:
  29212. case VertexBuffer.UNSIGNED_SHORT:
  29213. return 2;
  29214. case VertexBuffer.INT:
  29215. case VertexBuffer.FLOAT:
  29216. return 4;
  29217. default:
  29218. throw new Error("Invalid type '" + type + "'");
  29219. }
  29220. };
  29221. /**
  29222. * Enumerates each value of the given parameters as numbers.
  29223. * @param data the data to enumerate
  29224. * @param byteOffset the byte offset of the data
  29225. * @param byteStride the byte stride of the data
  29226. * @param componentCount the number of components per element
  29227. * @param componentType the type of the component
  29228. * @param count the total number of components
  29229. * @param normalized whether the data is normalized
  29230. * @param callback the callback function called for each value
  29231. */
  29232. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29233. if (data instanceof Array) {
  29234. var offset = byteOffset / 4;
  29235. var stride = byteStride / 4;
  29236. for (var index = 0; index < count; index += componentCount) {
  29237. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29238. callback(data[offset + componentIndex], index + componentIndex);
  29239. }
  29240. offset += stride;
  29241. }
  29242. }
  29243. else {
  29244. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29245. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29246. for (var index = 0; index < count; index += componentCount) {
  29247. var componentByteOffset = byteOffset;
  29248. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29249. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29250. callback(value, index + componentIndex);
  29251. componentByteOffset += componentByteLength;
  29252. }
  29253. byteOffset += byteStride;
  29254. }
  29255. }
  29256. };
  29257. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29258. switch (type) {
  29259. case VertexBuffer.BYTE: {
  29260. var value = dataView.getInt8(byteOffset);
  29261. if (normalized) {
  29262. value = (value + 0.5) / 127.5;
  29263. }
  29264. return value;
  29265. }
  29266. case VertexBuffer.UNSIGNED_BYTE: {
  29267. var value = dataView.getUint8(byteOffset);
  29268. if (normalized) {
  29269. value = value / 255;
  29270. }
  29271. return value;
  29272. }
  29273. case VertexBuffer.SHORT: {
  29274. var value = dataView.getInt16(byteOffset, true);
  29275. if (normalized) {
  29276. value = (value + 0.5) / 16383.5;
  29277. }
  29278. return value;
  29279. }
  29280. case VertexBuffer.UNSIGNED_SHORT: {
  29281. var value = dataView.getUint16(byteOffset, true);
  29282. if (normalized) {
  29283. value = value / 65535;
  29284. }
  29285. return value;
  29286. }
  29287. case VertexBuffer.FLOAT: {
  29288. return dataView.getFloat32(byteOffset, true);
  29289. }
  29290. default: {
  29291. throw new Error("Invalid component type " + type);
  29292. }
  29293. }
  29294. };
  29295. /**
  29296. * The byte type.
  29297. */
  29298. VertexBuffer.BYTE = 5120;
  29299. /**
  29300. * The unsigned byte type.
  29301. */
  29302. VertexBuffer.UNSIGNED_BYTE = 5121;
  29303. /**
  29304. * The short type.
  29305. */
  29306. VertexBuffer.SHORT = 5122;
  29307. /**
  29308. * The unsigned short type.
  29309. */
  29310. VertexBuffer.UNSIGNED_SHORT = 5123;
  29311. /**
  29312. * The integer type.
  29313. */
  29314. VertexBuffer.INT = 5124;
  29315. /**
  29316. * The unsigned integer type.
  29317. */
  29318. VertexBuffer.UNSIGNED_INT = 5125;
  29319. /**
  29320. * The float type.
  29321. */
  29322. VertexBuffer.FLOAT = 5126;
  29323. // Enums
  29324. VertexBuffer._PositionKind = "position";
  29325. VertexBuffer._NormalKind = "normal";
  29326. VertexBuffer._TangentKind = "tangent";
  29327. VertexBuffer._UVKind = "uv";
  29328. VertexBuffer._UV2Kind = "uv2";
  29329. VertexBuffer._UV3Kind = "uv3";
  29330. VertexBuffer._UV4Kind = "uv4";
  29331. VertexBuffer._UV5Kind = "uv5";
  29332. VertexBuffer._UV6Kind = "uv6";
  29333. VertexBuffer._ColorKind = "color";
  29334. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29335. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29336. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29337. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29338. return VertexBuffer;
  29339. }());
  29340. BABYLON.VertexBuffer = VertexBuffer;
  29341. })(BABYLON || (BABYLON = {}));
  29342. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. /**
  29346. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29347. */
  29348. var DummyInternalTextureTracker = /** @class */ (function () {
  29349. function DummyInternalTextureTracker() {
  29350. /**
  29351. * Gets or set the previous tracker in the list
  29352. */
  29353. this.previous = null;
  29354. /**
  29355. * Gets or set the next tracker in the list
  29356. */
  29357. this.next = null;
  29358. }
  29359. return DummyInternalTextureTracker;
  29360. }());
  29361. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29362. })(BABYLON || (BABYLON = {}));
  29363. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29364. var BABYLON;
  29365. (function (BABYLON) {
  29366. /**
  29367. * Class used to store data associated with WebGL texture data for the engine
  29368. * This class should not be used directly
  29369. */
  29370. var InternalTexture = /** @class */ (function () {
  29371. /**
  29372. * Creates a new InternalTexture
  29373. * @param engine defines the engine to use
  29374. * @param dataSource defines the type of data that will be used
  29375. */
  29376. function InternalTexture(engine, dataSource) {
  29377. /**
  29378. * Observable called when the texture is loaded
  29379. */
  29380. this.onLoadedObservable = new BABYLON.Observable();
  29381. /**
  29382. * Gets or set the previous tracker in the list
  29383. */
  29384. this.previous = null;
  29385. /**
  29386. * Gets or set the next tracker in the list
  29387. */
  29388. this.next = null;
  29389. // Private
  29390. /** @ignore */
  29391. this._initialSlot = -1;
  29392. /** @ignore */
  29393. this._designatedSlot = -1;
  29394. /** @ignore */
  29395. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29396. /** @ignore */
  29397. this._comparisonFunction = 0;
  29398. /** @ignore */
  29399. this._references = 1;
  29400. this._engine = engine;
  29401. this._dataSource = dataSource;
  29402. this._webGLTexture = engine._createTexture();
  29403. }
  29404. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29405. /**
  29406. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29407. */
  29408. get: function () {
  29409. return this._dataSource;
  29410. },
  29411. enumerable: true,
  29412. configurable: true
  29413. });
  29414. /**
  29415. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29416. */
  29417. InternalTexture.prototype.incrementReferences = function () {
  29418. this._references++;
  29419. };
  29420. /**
  29421. * Change the size of the texture (not the size of the content)
  29422. * @param width defines the new width
  29423. * @param height defines the new height
  29424. * @param depth defines the new depth (1 by default)
  29425. */
  29426. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29427. if (depth === void 0) { depth = 1; }
  29428. this.width = width;
  29429. this.height = height;
  29430. this.depth = depth;
  29431. this.baseWidth = width;
  29432. this.baseHeight = height;
  29433. this.baseDepth = depth;
  29434. this._size = width * height * depth;
  29435. };
  29436. /** @ignore */
  29437. InternalTexture.prototype._rebuild = function () {
  29438. var _this = this;
  29439. var proxy;
  29440. this.isReady = false;
  29441. this._cachedCoordinatesMode = null;
  29442. this._cachedWrapU = null;
  29443. this._cachedWrapV = null;
  29444. this._cachedAnisotropicFilteringLevel = null;
  29445. switch (this._dataSource) {
  29446. case InternalTexture.DATASOURCE_TEMP:
  29447. return;
  29448. case InternalTexture.DATASOURCE_URL:
  29449. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29450. _this.isReady = true;
  29451. }, null, this._buffer, undefined, this.format);
  29452. proxy._swapAndDie(this);
  29453. return;
  29454. case InternalTexture.DATASOURCE_RAW:
  29455. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29456. proxy._swapAndDie(this);
  29457. this.isReady = true;
  29458. return;
  29459. case InternalTexture.DATASOURCE_RAW3D:
  29460. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29461. proxy._swapAndDie(this);
  29462. this.isReady = true;
  29463. return;
  29464. case InternalTexture.DATASOURCE_DYNAMIC:
  29465. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29466. proxy._swapAndDie(this);
  29467. // The engine will make sure to update content so no need to flag it as isReady = true
  29468. return;
  29469. case InternalTexture.DATASOURCE_RENDERTARGET:
  29470. var options = new BABYLON.RenderTargetCreationOptions();
  29471. options.generateDepthBuffer = this._generateDepthBuffer;
  29472. options.generateMipMaps = this.generateMipMaps;
  29473. options.generateStencilBuffer = this._generateStencilBuffer;
  29474. options.samplingMode = this.samplingMode;
  29475. options.type = this.type;
  29476. if (this.isCube) {
  29477. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29478. }
  29479. else {
  29480. var size = {
  29481. width: this.width,
  29482. height: this.height
  29483. };
  29484. proxy = this._engine.createRenderTargetTexture(size, options);
  29485. }
  29486. proxy._swapAndDie(this);
  29487. this.isReady = true;
  29488. return;
  29489. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29490. var depthTextureOptions = {
  29491. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29492. comparisonFunction: this._comparisonFunction,
  29493. generateStencil: this._generateStencilBuffer,
  29494. isCube: this.isCube
  29495. };
  29496. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29497. proxy._swapAndDie(this);
  29498. this.isReady = true;
  29499. return;
  29500. case InternalTexture.DATASOURCE_CUBE:
  29501. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29502. _this.isReady = true;
  29503. }, null, this.format, this._extension);
  29504. proxy._swapAndDie(this);
  29505. return;
  29506. case InternalTexture.DATASOURCE_CUBERAW:
  29507. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29508. proxy._swapAndDie(this);
  29509. this.isReady = true;
  29510. return;
  29511. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29512. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29513. if (proxy) {
  29514. proxy._swapAndDie(_this);
  29515. }
  29516. _this.isReady = true;
  29517. }, null, this.format, this._extension);
  29518. return;
  29519. }
  29520. };
  29521. InternalTexture.prototype._swapAndDie = function (target) {
  29522. target._webGLTexture = this._webGLTexture;
  29523. if (this._framebuffer) {
  29524. target._framebuffer = this._framebuffer;
  29525. }
  29526. if (this._depthStencilBuffer) {
  29527. target._depthStencilBuffer = this._depthStencilBuffer;
  29528. }
  29529. if (this._lodTextureHigh) {
  29530. if (target._lodTextureHigh) {
  29531. target._lodTextureHigh.dispose();
  29532. }
  29533. target._lodTextureHigh = this._lodTextureHigh;
  29534. }
  29535. if (this._lodTextureMid) {
  29536. if (target._lodTextureMid) {
  29537. target._lodTextureMid.dispose();
  29538. }
  29539. target._lodTextureMid = this._lodTextureMid;
  29540. }
  29541. if (this._lodTextureLow) {
  29542. if (target._lodTextureLow) {
  29543. target._lodTextureLow.dispose();
  29544. }
  29545. target._lodTextureLow = this._lodTextureLow;
  29546. }
  29547. var cache = this._engine.getLoadedTexturesCache();
  29548. var index = cache.indexOf(this);
  29549. if (index !== -1) {
  29550. cache.splice(index, 1);
  29551. }
  29552. };
  29553. /**
  29554. * Dispose the current allocated resources
  29555. */
  29556. InternalTexture.prototype.dispose = function () {
  29557. if (!this._webGLTexture) {
  29558. return;
  29559. }
  29560. this._references--;
  29561. if (this._references === 0) {
  29562. this._engine._releaseTexture(this);
  29563. this._webGLTexture = null;
  29564. this.previous = null;
  29565. this.next = null;
  29566. }
  29567. };
  29568. /**
  29569. * The source of the texture data is unknown
  29570. */
  29571. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29572. /**
  29573. * Texture data comes from an URL
  29574. */
  29575. InternalTexture.DATASOURCE_URL = 1;
  29576. /**
  29577. * Texture data is only used for temporary storage
  29578. */
  29579. InternalTexture.DATASOURCE_TEMP = 2;
  29580. /**
  29581. * Texture data comes from raw data (ArrayBuffer)
  29582. */
  29583. InternalTexture.DATASOURCE_RAW = 3;
  29584. /**
  29585. * Texture content is dynamic (video or dynamic texture)
  29586. */
  29587. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29588. /**
  29589. * Texture content is generated by rendering to it
  29590. */
  29591. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29592. /**
  29593. * Texture content is part of a multi render target process
  29594. */
  29595. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29596. /**
  29597. * Texture data comes from a cube data file
  29598. */
  29599. InternalTexture.DATASOURCE_CUBE = 7;
  29600. /**
  29601. * Texture data comes from a raw cube data
  29602. */
  29603. InternalTexture.DATASOURCE_CUBERAW = 8;
  29604. /**
  29605. * Texture data come from a prefiltered cube data file
  29606. */
  29607. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29608. /**
  29609. * Texture content is raw 3D data
  29610. */
  29611. InternalTexture.DATASOURCE_RAW3D = 10;
  29612. /**
  29613. * Texture content is a depth texture
  29614. */
  29615. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29616. return InternalTexture;
  29617. }());
  29618. BABYLON.InternalTexture = InternalTexture;
  29619. })(BABYLON || (BABYLON = {}));
  29620. //# sourceMappingURL=babylon.internalTexture.js.map
  29621. var BABYLON;
  29622. (function (BABYLON) {
  29623. var BaseTexture = /** @class */ (function () {
  29624. function BaseTexture(scene) {
  29625. this._hasAlpha = false;
  29626. this.getAlphaFromRGB = false;
  29627. this.level = 1;
  29628. this.coordinatesIndex = 0;
  29629. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29630. /**
  29631. * | Value | Type | Description |
  29632. * | ----- | ------------------ | ----------- |
  29633. * | 0 | CLAMP_ADDRESSMODE | |
  29634. * | 1 | WRAP_ADDRESSMODE | |
  29635. * | 2 | MIRROR_ADDRESSMODE | |
  29636. */
  29637. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29638. /**
  29639. * | Value | Type | Description |
  29640. * | ----- | ------------------ | ----------- |
  29641. * | 0 | CLAMP_ADDRESSMODE | |
  29642. * | 1 | WRAP_ADDRESSMODE | |
  29643. * | 2 | MIRROR_ADDRESSMODE | |
  29644. */
  29645. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29646. /**
  29647. * | Value | Type | Description |
  29648. * | ----- | ------------------ | ----------- |
  29649. * | 0 | CLAMP_ADDRESSMODE | |
  29650. * | 1 | WRAP_ADDRESSMODE | |
  29651. * | 2 | MIRROR_ADDRESSMODE | |
  29652. */
  29653. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29654. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29655. this.isCube = false;
  29656. this.is3D = false;
  29657. this.gammaSpace = true;
  29658. this.invertZ = false;
  29659. this.lodLevelInAlpha = false;
  29660. this.lodGenerationOffset = 0.0;
  29661. this.lodGenerationScale = 0.8;
  29662. this.isRenderTarget = false;
  29663. this.animations = new Array();
  29664. /**
  29665. * An event triggered when the texture is disposed.
  29666. */
  29667. this.onDisposeObservable = new BABYLON.Observable();
  29668. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29669. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29670. if (this._scene) {
  29671. this._scene.textures.push(this);
  29672. }
  29673. this._uid = null;
  29674. }
  29675. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29676. get: function () {
  29677. return this._hasAlpha;
  29678. },
  29679. set: function (value) {
  29680. if (this._hasAlpha === value) {
  29681. return;
  29682. }
  29683. this._hasAlpha = value;
  29684. if (this._scene) {
  29685. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29686. }
  29687. },
  29688. enumerable: true,
  29689. configurable: true
  29690. });
  29691. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29692. get: function () {
  29693. return this._coordinatesMode;
  29694. },
  29695. /**
  29696. * How a texture is mapped.
  29697. *
  29698. * | Value | Type | Description |
  29699. * | ----- | ----------------------------------- | ----------- |
  29700. * | 0 | EXPLICIT_MODE | |
  29701. * | 1 | SPHERICAL_MODE | |
  29702. * | 2 | PLANAR_MODE | |
  29703. * | 3 | CUBIC_MODE | |
  29704. * | 4 | PROJECTION_MODE | |
  29705. * | 5 | SKYBOX_MODE | |
  29706. * | 6 | INVCUBIC_MODE | |
  29707. * | 7 | EQUIRECTANGULAR_MODE | |
  29708. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29709. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29710. */
  29711. set: function (value) {
  29712. if (this._coordinatesMode === value) {
  29713. return;
  29714. }
  29715. this._coordinatesMode = value;
  29716. if (this._scene) {
  29717. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29718. }
  29719. },
  29720. enumerable: true,
  29721. configurable: true
  29722. });
  29723. Object.defineProperty(BaseTexture.prototype, "uid", {
  29724. get: function () {
  29725. if (!this._uid) {
  29726. this._uid = BABYLON.Tools.RandomId();
  29727. }
  29728. return this._uid;
  29729. },
  29730. enumerable: true,
  29731. configurable: true
  29732. });
  29733. BaseTexture.prototype.toString = function () {
  29734. return this.name;
  29735. };
  29736. BaseTexture.prototype.getClassName = function () {
  29737. return "BaseTexture";
  29738. };
  29739. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29740. set: function (callback) {
  29741. if (this._onDisposeObserver) {
  29742. this.onDisposeObservable.remove(this._onDisposeObserver);
  29743. }
  29744. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29745. },
  29746. enumerable: true,
  29747. configurable: true
  29748. });
  29749. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29750. get: function () {
  29751. return true;
  29752. },
  29753. enumerable: true,
  29754. configurable: true
  29755. });
  29756. BaseTexture.prototype.getScene = function () {
  29757. return this._scene;
  29758. };
  29759. BaseTexture.prototype.getTextureMatrix = function () {
  29760. return BABYLON.Matrix.IdentityReadOnly;
  29761. };
  29762. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29763. return BABYLON.Matrix.IdentityReadOnly;
  29764. };
  29765. BaseTexture.prototype.getInternalTexture = function () {
  29766. return this._texture;
  29767. };
  29768. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29769. return !this.isBlocking || this.isReady();
  29770. };
  29771. BaseTexture.prototype.isReady = function () {
  29772. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29773. this.delayLoad();
  29774. return false;
  29775. }
  29776. if (this._texture) {
  29777. return this._texture.isReady;
  29778. }
  29779. return false;
  29780. };
  29781. BaseTexture.prototype.getSize = function () {
  29782. if (this._texture && this._texture.width) {
  29783. return new BABYLON.Size(this._texture.width, this._texture.height);
  29784. }
  29785. if (this._texture && this._texture._size) {
  29786. return new BABYLON.Size(this._texture._size, this._texture._size);
  29787. }
  29788. return BABYLON.Size.Zero();
  29789. };
  29790. BaseTexture.prototype.getBaseSize = function () {
  29791. if (!this.isReady() || !this._texture)
  29792. return BABYLON.Size.Zero();
  29793. if (this._texture._size) {
  29794. return new BABYLON.Size(this._texture._size, this._texture._size);
  29795. }
  29796. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29797. };
  29798. BaseTexture.prototype.scale = function (ratio) {
  29799. };
  29800. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29801. get: function () {
  29802. return false;
  29803. },
  29804. enumerable: true,
  29805. configurable: true
  29806. });
  29807. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29808. if (!this._scene) {
  29809. return null;
  29810. }
  29811. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29812. for (var index = 0; index < texturesCache.length; index++) {
  29813. var texturesCacheEntry = texturesCache[index];
  29814. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29815. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29816. texturesCacheEntry.incrementReferences();
  29817. return texturesCacheEntry;
  29818. }
  29819. }
  29820. }
  29821. return null;
  29822. };
  29823. BaseTexture.prototype._rebuild = function () {
  29824. };
  29825. BaseTexture.prototype.delayLoad = function () {
  29826. };
  29827. BaseTexture.prototype.clone = function () {
  29828. return null;
  29829. };
  29830. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29831. get: function () {
  29832. if (!this._texture) {
  29833. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29834. }
  29835. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29836. },
  29837. enumerable: true,
  29838. configurable: true
  29839. });
  29840. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29841. get: function () {
  29842. if (!this._texture) {
  29843. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29844. }
  29845. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29846. },
  29847. enumerable: true,
  29848. configurable: true
  29849. });
  29850. BaseTexture.prototype.readPixels = function (faceIndex) {
  29851. if (faceIndex === void 0) { faceIndex = 0; }
  29852. if (!this._texture) {
  29853. return null;
  29854. }
  29855. var size = this.getSize();
  29856. var scene = this.getScene();
  29857. if (!scene) {
  29858. return null;
  29859. }
  29860. var engine = scene.getEngine();
  29861. if (this._texture.isCube) {
  29862. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29863. }
  29864. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29865. };
  29866. BaseTexture.prototype.releaseInternalTexture = function () {
  29867. if (this._texture) {
  29868. this._texture.dispose();
  29869. this._texture = null;
  29870. }
  29871. };
  29872. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29873. get: function () {
  29874. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  29875. return null;
  29876. }
  29877. if (!this._texture._sphericalPolynomial) {
  29878. this._texture._sphericalPolynomial =
  29879. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  29880. }
  29881. return this._texture._sphericalPolynomial;
  29882. },
  29883. set: function (value) {
  29884. if (this._texture) {
  29885. this._texture._sphericalPolynomial = value;
  29886. }
  29887. },
  29888. enumerable: true,
  29889. configurable: true
  29890. });
  29891. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  29892. get: function () {
  29893. if (this._texture) {
  29894. return this._texture._lodTextureHigh;
  29895. }
  29896. return null;
  29897. },
  29898. enumerable: true,
  29899. configurable: true
  29900. });
  29901. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  29902. get: function () {
  29903. if (this._texture) {
  29904. return this._texture._lodTextureMid;
  29905. }
  29906. return null;
  29907. },
  29908. enumerable: true,
  29909. configurable: true
  29910. });
  29911. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  29912. get: function () {
  29913. if (this._texture) {
  29914. return this._texture._lodTextureLow;
  29915. }
  29916. return null;
  29917. },
  29918. enumerable: true,
  29919. configurable: true
  29920. });
  29921. BaseTexture.prototype.dispose = function () {
  29922. if (!this._scene) {
  29923. return;
  29924. }
  29925. // Animations
  29926. this._scene.stopAnimation(this);
  29927. // Remove from scene
  29928. this._scene._removePendingData(this);
  29929. var index = this._scene.textures.indexOf(this);
  29930. if (index >= 0) {
  29931. this._scene.textures.splice(index, 1);
  29932. }
  29933. if (this._texture === undefined) {
  29934. return;
  29935. }
  29936. // Release
  29937. this.releaseInternalTexture();
  29938. // Callback
  29939. this.onDisposeObservable.notifyObservers(this);
  29940. this.onDisposeObservable.clear();
  29941. };
  29942. BaseTexture.prototype.serialize = function () {
  29943. if (!this.name) {
  29944. return null;
  29945. }
  29946. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  29947. // Animations
  29948. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29949. return serializationObject;
  29950. };
  29951. BaseTexture.WhenAllReady = function (textures, callback) {
  29952. var numRemaining = textures.length;
  29953. if (numRemaining === 0) {
  29954. callback();
  29955. return;
  29956. }
  29957. var _loop_1 = function () {
  29958. texture = textures[i];
  29959. if (texture.isReady()) {
  29960. if (--numRemaining === 0) {
  29961. callback();
  29962. }
  29963. }
  29964. else {
  29965. onLoadObservable = texture.onLoadObservable;
  29966. var onLoadCallback_1 = function () {
  29967. onLoadObservable.removeCallback(onLoadCallback_1);
  29968. if (--numRemaining === 0) {
  29969. callback();
  29970. }
  29971. };
  29972. onLoadObservable.add(onLoadCallback_1);
  29973. }
  29974. };
  29975. var texture, onLoadObservable;
  29976. for (var i = 0; i < textures.length; i++) {
  29977. _loop_1();
  29978. }
  29979. };
  29980. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  29981. __decorate([
  29982. BABYLON.serialize()
  29983. ], BaseTexture.prototype, "name", void 0);
  29984. __decorate([
  29985. BABYLON.serialize("hasAlpha")
  29986. ], BaseTexture.prototype, "_hasAlpha", void 0);
  29987. __decorate([
  29988. BABYLON.serialize()
  29989. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  29990. __decorate([
  29991. BABYLON.serialize()
  29992. ], BaseTexture.prototype, "level", void 0);
  29993. __decorate([
  29994. BABYLON.serialize()
  29995. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  29996. __decorate([
  29997. BABYLON.serialize("coordinatesMode")
  29998. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  29999. __decorate([
  30000. BABYLON.serialize()
  30001. ], BaseTexture.prototype, "wrapU", void 0);
  30002. __decorate([
  30003. BABYLON.serialize()
  30004. ], BaseTexture.prototype, "wrapV", void 0);
  30005. __decorate([
  30006. BABYLON.serialize()
  30007. ], BaseTexture.prototype, "wrapR", void 0);
  30008. __decorate([
  30009. BABYLON.serialize()
  30010. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30011. __decorate([
  30012. BABYLON.serialize()
  30013. ], BaseTexture.prototype, "isCube", void 0);
  30014. __decorate([
  30015. BABYLON.serialize()
  30016. ], BaseTexture.prototype, "is3D", void 0);
  30017. __decorate([
  30018. BABYLON.serialize()
  30019. ], BaseTexture.prototype, "gammaSpace", void 0);
  30020. __decorate([
  30021. BABYLON.serialize()
  30022. ], BaseTexture.prototype, "invertZ", void 0);
  30023. __decorate([
  30024. BABYLON.serialize()
  30025. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30026. __decorate([
  30027. BABYLON.serialize()
  30028. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30029. __decorate([
  30030. BABYLON.serialize()
  30031. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30032. __decorate([
  30033. BABYLON.serialize()
  30034. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30035. return BaseTexture;
  30036. }());
  30037. BABYLON.BaseTexture = BaseTexture;
  30038. })(BABYLON || (BABYLON = {}));
  30039. //# sourceMappingURL=babylon.baseTexture.js.map
  30040. var BABYLON;
  30041. (function (BABYLON) {
  30042. var Texture = /** @class */ (function (_super) {
  30043. __extends(Texture, _super);
  30044. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30045. if (noMipmap === void 0) { noMipmap = false; }
  30046. if (invertY === void 0) { invertY = true; }
  30047. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30048. if (onLoad === void 0) { onLoad = null; }
  30049. if (onError === void 0) { onError = null; }
  30050. if (buffer === void 0) { buffer = null; }
  30051. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30052. var _this = _super.call(this, scene) || this;
  30053. _this.uOffset = 0;
  30054. _this.vOffset = 0;
  30055. _this.uScale = 1.0;
  30056. _this.vScale = 1.0;
  30057. _this.uAng = 0;
  30058. _this.vAng = 0;
  30059. _this.wAng = 0;
  30060. _this._isBlocking = true;
  30061. _this.name = url || "";
  30062. _this.url = url;
  30063. _this._noMipmap = noMipmap;
  30064. _this._invertY = invertY;
  30065. _this._samplingMode = samplingMode;
  30066. _this._buffer = buffer;
  30067. _this._deleteBuffer = deleteBuffer;
  30068. if (format) {
  30069. _this._format = format;
  30070. }
  30071. scene = _this.getScene();
  30072. if (!scene) {
  30073. return _this;
  30074. }
  30075. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30076. var load = function () {
  30077. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30078. _this.onLoadObservable.notifyObservers(_this);
  30079. }
  30080. if (onLoad) {
  30081. onLoad();
  30082. }
  30083. if (!_this.isBlocking && scene) {
  30084. scene.resetCachedMaterial();
  30085. }
  30086. };
  30087. if (!_this.url) {
  30088. _this._delayedOnLoad = load;
  30089. _this._delayedOnError = onError;
  30090. return _this;
  30091. }
  30092. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30093. if (!_this._texture) {
  30094. if (!scene.useDelayedTextureLoading) {
  30095. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30096. if (deleteBuffer) {
  30097. delete _this._buffer;
  30098. }
  30099. }
  30100. else {
  30101. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30102. _this._delayedOnLoad = load;
  30103. _this._delayedOnError = onError;
  30104. }
  30105. }
  30106. else {
  30107. if (_this._texture.isReady) {
  30108. BABYLON.Tools.SetImmediate(function () { return load(); });
  30109. }
  30110. else {
  30111. _this._texture.onLoadedObservable.add(load);
  30112. }
  30113. }
  30114. return _this;
  30115. }
  30116. Object.defineProperty(Texture.prototype, "noMipmap", {
  30117. get: function () {
  30118. return this._noMipmap;
  30119. },
  30120. enumerable: true,
  30121. configurable: true
  30122. });
  30123. Object.defineProperty(Texture.prototype, "isBlocking", {
  30124. get: function () {
  30125. return this._isBlocking;
  30126. },
  30127. set: function (value) {
  30128. this._isBlocking = value;
  30129. },
  30130. enumerable: true,
  30131. configurable: true
  30132. });
  30133. Object.defineProperty(Texture.prototype, "samplingMode", {
  30134. get: function () {
  30135. return this._samplingMode;
  30136. },
  30137. enumerable: true,
  30138. configurable: true
  30139. });
  30140. Texture.prototype.updateURL = function (url) {
  30141. this.url = url;
  30142. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30143. this.delayLoad();
  30144. };
  30145. Texture.prototype.delayLoad = function () {
  30146. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30147. return;
  30148. }
  30149. var scene = this.getScene();
  30150. if (!scene) {
  30151. return;
  30152. }
  30153. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30154. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30155. if (!this._texture) {
  30156. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30157. if (this._deleteBuffer) {
  30158. delete this._buffer;
  30159. }
  30160. }
  30161. else {
  30162. if (this._delayedOnLoad) {
  30163. if (this._texture.isReady) {
  30164. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30165. }
  30166. else {
  30167. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30168. }
  30169. }
  30170. }
  30171. this._delayedOnLoad = null;
  30172. this._delayedOnError = null;
  30173. };
  30174. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30175. if (!this._texture) {
  30176. return;
  30177. }
  30178. var scene = this.getScene();
  30179. if (!scene) {
  30180. return;
  30181. }
  30182. this._samplingMode = samplingMode;
  30183. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30184. };
  30185. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30186. x *= this.uScale;
  30187. y *= this.vScale;
  30188. x -= 0.5 * this.uScale;
  30189. y -= 0.5 * this.vScale;
  30190. z -= 0.5;
  30191. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30192. t.x += 0.5 * this.uScale + this.uOffset;
  30193. t.y += 0.5 * this.vScale + this.vOffset;
  30194. t.z += 0.5;
  30195. };
  30196. Texture.prototype.getTextureMatrix = function () {
  30197. var _this = this;
  30198. if (this.uOffset === this._cachedUOffset &&
  30199. this.vOffset === this._cachedVOffset &&
  30200. this.uScale === this._cachedUScale &&
  30201. this.vScale === this._cachedVScale &&
  30202. this.uAng === this._cachedUAng &&
  30203. this.vAng === this._cachedVAng &&
  30204. this.wAng === this._cachedWAng) {
  30205. return this._cachedTextureMatrix;
  30206. }
  30207. this._cachedUOffset = this.uOffset;
  30208. this._cachedVOffset = this.vOffset;
  30209. this._cachedUScale = this.uScale;
  30210. this._cachedVScale = this.vScale;
  30211. this._cachedUAng = this.uAng;
  30212. this._cachedVAng = this.vAng;
  30213. this._cachedWAng = this.wAng;
  30214. if (!this._cachedTextureMatrix) {
  30215. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30216. this._rowGenerationMatrix = new BABYLON.Matrix();
  30217. this._t0 = BABYLON.Vector3.Zero();
  30218. this._t1 = BABYLON.Vector3.Zero();
  30219. this._t2 = BABYLON.Vector3.Zero();
  30220. }
  30221. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30222. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30223. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30224. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30225. this._t1.subtractInPlace(this._t0);
  30226. this._t2.subtractInPlace(this._t0);
  30227. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30228. this._cachedTextureMatrix.m[0] = this._t1.x;
  30229. this._cachedTextureMatrix.m[1] = this._t1.y;
  30230. this._cachedTextureMatrix.m[2] = this._t1.z;
  30231. this._cachedTextureMatrix.m[4] = this._t2.x;
  30232. this._cachedTextureMatrix.m[5] = this._t2.y;
  30233. this._cachedTextureMatrix.m[6] = this._t2.z;
  30234. this._cachedTextureMatrix.m[8] = this._t0.x;
  30235. this._cachedTextureMatrix.m[9] = this._t0.y;
  30236. this._cachedTextureMatrix.m[10] = this._t0.z;
  30237. var scene = this.getScene();
  30238. if (!scene) {
  30239. return this._cachedTextureMatrix;
  30240. }
  30241. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30242. return mat.hasTexture(_this);
  30243. });
  30244. return this._cachedTextureMatrix;
  30245. };
  30246. Texture.prototype.getReflectionTextureMatrix = function () {
  30247. var _this = this;
  30248. var scene = this.getScene();
  30249. if (!scene) {
  30250. return this._cachedTextureMatrix;
  30251. }
  30252. if (this.uOffset === this._cachedUOffset &&
  30253. this.vOffset === this._cachedVOffset &&
  30254. this.uScale === this._cachedUScale &&
  30255. this.vScale === this._cachedVScale &&
  30256. this.coordinatesMode === this._cachedCoordinatesMode) {
  30257. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30258. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30259. return this._cachedTextureMatrix;
  30260. }
  30261. }
  30262. else {
  30263. return this._cachedTextureMatrix;
  30264. }
  30265. }
  30266. if (!this._cachedTextureMatrix) {
  30267. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30268. }
  30269. if (!this._projectionModeMatrix) {
  30270. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30271. }
  30272. this._cachedUOffset = this.uOffset;
  30273. this._cachedVOffset = this.vOffset;
  30274. this._cachedUScale = this.uScale;
  30275. this._cachedVScale = this.vScale;
  30276. this._cachedCoordinatesMode = this.coordinatesMode;
  30277. switch (this.coordinatesMode) {
  30278. case Texture.PLANAR_MODE:
  30279. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30280. this._cachedTextureMatrix[0] = this.uScale;
  30281. this._cachedTextureMatrix[5] = this.vScale;
  30282. this._cachedTextureMatrix[12] = this.uOffset;
  30283. this._cachedTextureMatrix[13] = this.vOffset;
  30284. break;
  30285. case Texture.PROJECTION_MODE:
  30286. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30287. this._projectionModeMatrix.m[0] = 0.5;
  30288. this._projectionModeMatrix.m[5] = -0.5;
  30289. this._projectionModeMatrix.m[10] = 0.0;
  30290. this._projectionModeMatrix.m[12] = 0.5;
  30291. this._projectionModeMatrix.m[13] = 0.5;
  30292. this._projectionModeMatrix.m[14] = 1.0;
  30293. this._projectionModeMatrix.m[15] = 1.0;
  30294. var projectionMatrix = scene.getProjectionMatrix();
  30295. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30296. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30297. break;
  30298. default:
  30299. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30300. break;
  30301. }
  30302. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30303. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30304. });
  30305. return this._cachedTextureMatrix;
  30306. };
  30307. Texture.prototype.clone = function () {
  30308. var _this = this;
  30309. return BABYLON.SerializationHelper.Clone(function () {
  30310. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30311. }, this);
  30312. };
  30313. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30314. get: function () {
  30315. if (!this._onLoadObservable) {
  30316. this._onLoadObservable = new BABYLON.Observable();
  30317. }
  30318. return this._onLoadObservable;
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. Texture.prototype.serialize = function () {
  30324. var serializationObject = _super.prototype.serialize.call(this);
  30325. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30326. serializationObject.base64String = this._buffer;
  30327. serializationObject.name = serializationObject.name.replace("data:", "");
  30328. }
  30329. serializationObject.invertY = this._invertY;
  30330. serializationObject.samplingMode = this.samplingMode;
  30331. return serializationObject;
  30332. };
  30333. Texture.prototype.getClassName = function () {
  30334. return "Texture";
  30335. };
  30336. Texture.prototype.dispose = function () {
  30337. _super.prototype.dispose.call(this);
  30338. if (this.onLoadObservable) {
  30339. this.onLoadObservable.clear();
  30340. this._onLoadObservable = null;
  30341. }
  30342. this._delayedOnLoad = null;
  30343. this._delayedOnError = null;
  30344. };
  30345. // Statics
  30346. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30347. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30348. if (onLoad === void 0) { onLoad = null; }
  30349. if (onError === void 0) { onError = null; }
  30350. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30351. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30352. };
  30353. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30354. if (parsedTexture.customType) {
  30355. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30356. // Update Sampling Mode
  30357. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30358. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30359. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30360. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30361. }
  30362. }
  30363. return parsedCustomTexture;
  30364. }
  30365. if (parsedTexture.isCube) {
  30366. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30367. }
  30368. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30369. return null;
  30370. }
  30371. var texture = BABYLON.SerializationHelper.Parse(function () {
  30372. var generateMipMaps = true;
  30373. if (parsedTexture.noMipmap) {
  30374. generateMipMaps = false;
  30375. }
  30376. if (parsedTexture.mirrorPlane) {
  30377. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30378. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30379. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30380. return mirrorTexture;
  30381. }
  30382. else if (parsedTexture.isRenderTarget) {
  30383. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30384. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30385. return renderTargetTexture;
  30386. }
  30387. else {
  30388. var texture;
  30389. if (parsedTexture.base64String) {
  30390. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30391. }
  30392. else {
  30393. var url = rootUrl + parsedTexture.name;
  30394. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30395. url = parsedTexture.url;
  30396. }
  30397. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30398. }
  30399. return texture;
  30400. }
  30401. }, parsedTexture, scene);
  30402. // Update Sampling Mode
  30403. if (parsedTexture.samplingMode) {
  30404. var sampling = parsedTexture.samplingMode;
  30405. if (texture._samplingMode !== sampling) {
  30406. texture.updateSamplingMode(sampling);
  30407. }
  30408. }
  30409. // Animations
  30410. if (parsedTexture.animations) {
  30411. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30412. var parsedAnimation = parsedTexture.animations[animationIndex];
  30413. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30414. }
  30415. }
  30416. return texture;
  30417. };
  30418. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30419. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30420. if (noMipmap === void 0) { noMipmap = false; }
  30421. if (invertY === void 0) { invertY = true; }
  30422. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30423. if (onLoad === void 0) { onLoad = null; }
  30424. if (onError === void 0) { onError = null; }
  30425. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30426. if (name.substr(0, 5) !== "data:") {
  30427. name = "data:" + name;
  30428. }
  30429. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30430. };
  30431. // Constants
  30432. Texture.NEAREST_SAMPLINGMODE = 1;
  30433. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30434. Texture.BILINEAR_SAMPLINGMODE = 2;
  30435. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30436. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30437. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30438. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30439. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30440. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30441. Texture.NEAREST_LINEAR = 7;
  30442. Texture.NEAREST_NEAREST = 8;
  30443. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30444. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30445. Texture.LINEAR_LINEAR = 11;
  30446. Texture.LINEAR_NEAREST = 12;
  30447. Texture.EXPLICIT_MODE = 0;
  30448. Texture.SPHERICAL_MODE = 1;
  30449. Texture.PLANAR_MODE = 2;
  30450. Texture.CUBIC_MODE = 3;
  30451. Texture.PROJECTION_MODE = 4;
  30452. Texture.SKYBOX_MODE = 5;
  30453. Texture.INVCUBIC_MODE = 6;
  30454. Texture.EQUIRECTANGULAR_MODE = 7;
  30455. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30456. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30457. Texture.CLAMP_ADDRESSMODE = 0;
  30458. Texture.WRAP_ADDRESSMODE = 1;
  30459. Texture.MIRROR_ADDRESSMODE = 2;
  30460. /**
  30461. * 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
  30462. */
  30463. Texture.UseSerializedUrlIfAny = false;
  30464. __decorate([
  30465. BABYLON.serialize()
  30466. ], Texture.prototype, "url", void 0);
  30467. __decorate([
  30468. BABYLON.serialize()
  30469. ], Texture.prototype, "uOffset", void 0);
  30470. __decorate([
  30471. BABYLON.serialize()
  30472. ], Texture.prototype, "vOffset", void 0);
  30473. __decorate([
  30474. BABYLON.serialize()
  30475. ], Texture.prototype, "uScale", void 0);
  30476. __decorate([
  30477. BABYLON.serialize()
  30478. ], Texture.prototype, "vScale", void 0);
  30479. __decorate([
  30480. BABYLON.serialize()
  30481. ], Texture.prototype, "uAng", void 0);
  30482. __decorate([
  30483. BABYLON.serialize()
  30484. ], Texture.prototype, "vAng", void 0);
  30485. __decorate([
  30486. BABYLON.serialize()
  30487. ], Texture.prototype, "wAng", void 0);
  30488. __decorate([
  30489. BABYLON.serialize()
  30490. ], Texture.prototype, "isBlocking", null);
  30491. return Texture;
  30492. }(BABYLON.BaseTexture));
  30493. BABYLON.Texture = Texture;
  30494. })(BABYLON || (BABYLON = {}));
  30495. //# sourceMappingURL=babylon.texture.js.map
  30496. var BABYLON;
  30497. (function (BABYLON) {
  30498. var _InstancesBatch = /** @class */ (function () {
  30499. function _InstancesBatch() {
  30500. this.mustReturn = false;
  30501. this.visibleInstances = new Array();
  30502. this.renderSelf = new Array();
  30503. }
  30504. return _InstancesBatch;
  30505. }());
  30506. BABYLON._InstancesBatch = _InstancesBatch;
  30507. var Mesh = /** @class */ (function (_super) {
  30508. __extends(Mesh, _super);
  30509. /**
  30510. * @constructor
  30511. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30512. * @param {Scene} scene The scene to add this mesh to.
  30513. * @param {Node} parent The parent of this mesh, if it has one
  30514. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30515. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30516. * When false, achieved by calling a clone(), also passing False.
  30517. * This will make creation of children, recursive.
  30518. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30519. */
  30520. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30521. if (scene === void 0) { scene = null; }
  30522. if (parent === void 0) { parent = null; }
  30523. if (source === void 0) { source = null; }
  30524. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30525. var _this = _super.call(this, name, scene) || this;
  30526. // Events
  30527. /**
  30528. * An event triggered before rendering the mesh
  30529. */
  30530. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30531. /**
  30532. * An event triggered after rendering the mesh
  30533. */
  30534. _this.onAfterRenderObservable = new BABYLON.Observable();
  30535. /**
  30536. * An event triggered before drawing the mesh
  30537. */
  30538. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30539. // Members
  30540. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30541. _this.instances = new Array();
  30542. _this._LODLevels = new Array();
  30543. _this._visibleInstances = {};
  30544. _this._renderIdForInstances = new Array();
  30545. _this._batchCache = new _InstancesBatch();
  30546. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30547. // Use by builder only to know what orientation were the mesh build in.
  30548. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30549. _this.overrideMaterialSideOrientation = null;
  30550. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30551. // Will be used to save a source mesh reference, If any
  30552. _this._source = null;
  30553. scene = _this.getScene();
  30554. if (source) {
  30555. // Source mesh
  30556. _this._source = source;
  30557. // Geometry
  30558. if (source._geometry) {
  30559. source._geometry.applyToMesh(_this);
  30560. }
  30561. // Deep copy
  30562. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30563. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30564. // Metadata
  30565. if (source.metadata && source.metadata.clone) {
  30566. _this.metadata = source.metadata.clone();
  30567. }
  30568. else {
  30569. _this.metadata = source.metadata;
  30570. }
  30571. // Tags
  30572. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30573. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30574. }
  30575. // Parent
  30576. _this.parent = source.parent;
  30577. // Pivot
  30578. _this.setPivotMatrix(source.getPivotMatrix());
  30579. _this.id = name + "." + source.id;
  30580. // Material
  30581. _this.material = source.material;
  30582. var index;
  30583. if (!doNotCloneChildren) {
  30584. // Children
  30585. var directDescendants = source.getDescendants(true);
  30586. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30587. var child = directDescendants[index_1];
  30588. if (child.clone) {
  30589. child.clone(name + "." + child.name, _this);
  30590. }
  30591. }
  30592. }
  30593. // Physics clone
  30594. var physicsEngine = _this.getScene().getPhysicsEngine();
  30595. if (clonePhysicsImpostor && physicsEngine) {
  30596. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30597. if (impostor) {
  30598. _this.physicsImpostor = impostor.clone(_this);
  30599. }
  30600. }
  30601. // Particles
  30602. for (index = 0; index < scene.particleSystems.length; index++) {
  30603. var system = scene.particleSystems[index];
  30604. if (system.emitter === source) {
  30605. system.clone(system.name, _this);
  30606. }
  30607. }
  30608. _this.computeWorldMatrix(true);
  30609. }
  30610. // Parent
  30611. if (parent !== null) {
  30612. _this.parent = parent;
  30613. }
  30614. return _this;
  30615. }
  30616. Object.defineProperty(Mesh, "FRONTSIDE", {
  30617. /**
  30618. * Mesh side orientation : usually the external or front surface
  30619. */
  30620. get: function () {
  30621. return Mesh._FRONTSIDE;
  30622. },
  30623. enumerable: true,
  30624. configurable: true
  30625. });
  30626. Object.defineProperty(Mesh, "BACKSIDE", {
  30627. /**
  30628. * Mesh side orientation : usually the internal or back surface
  30629. */
  30630. get: function () {
  30631. return Mesh._BACKSIDE;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30637. /**
  30638. * Mesh side orientation : both internal and external or front and back surfaces
  30639. */
  30640. get: function () {
  30641. return Mesh._DOUBLESIDE;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30647. /**
  30648. * Mesh side orientation : by default, `FRONTSIDE`
  30649. */
  30650. get: function () {
  30651. return Mesh._DEFAULTSIDE;
  30652. },
  30653. enumerable: true,
  30654. configurable: true
  30655. });
  30656. Object.defineProperty(Mesh, "NO_CAP", {
  30657. /**
  30658. * Mesh cap setting : no cap
  30659. */
  30660. get: function () {
  30661. return Mesh._NO_CAP;
  30662. },
  30663. enumerable: true,
  30664. configurable: true
  30665. });
  30666. Object.defineProperty(Mesh, "CAP_START", {
  30667. /**
  30668. * Mesh cap setting : one cap at the beginning of the mesh
  30669. */
  30670. get: function () {
  30671. return Mesh._CAP_START;
  30672. },
  30673. enumerable: true,
  30674. configurable: true
  30675. });
  30676. Object.defineProperty(Mesh, "CAP_END", {
  30677. /**
  30678. * Mesh cap setting : one cap at the end of the mesh
  30679. */
  30680. get: function () {
  30681. return Mesh._CAP_END;
  30682. },
  30683. enumerable: true,
  30684. configurable: true
  30685. });
  30686. Object.defineProperty(Mesh, "CAP_ALL", {
  30687. /**
  30688. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30689. */
  30690. get: function () {
  30691. return Mesh._CAP_ALL;
  30692. },
  30693. enumerable: true,
  30694. configurable: true
  30695. });
  30696. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30697. set: function (callback) {
  30698. if (this._onBeforeDrawObserver) {
  30699. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30700. }
  30701. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30702. },
  30703. enumerable: true,
  30704. configurable: true
  30705. });
  30706. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30707. get: function () {
  30708. return this._morphTargetManager;
  30709. },
  30710. set: function (value) {
  30711. if (this._morphTargetManager === value) {
  30712. return;
  30713. }
  30714. this._morphTargetManager = value;
  30715. this._syncGeometryWithMorphTargetManager();
  30716. },
  30717. enumerable: true,
  30718. configurable: true
  30719. });
  30720. Object.defineProperty(Mesh.prototype, "source", {
  30721. get: function () {
  30722. return this._source;
  30723. },
  30724. enumerable: true,
  30725. configurable: true
  30726. });
  30727. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30728. get: function () {
  30729. return this._unIndexed;
  30730. },
  30731. set: function (value) {
  30732. if (this._unIndexed !== value) {
  30733. this._unIndexed = value;
  30734. this._markSubMeshesAsAttributesDirty();
  30735. }
  30736. },
  30737. enumerable: true,
  30738. configurable: true
  30739. });
  30740. // Methods
  30741. /**
  30742. * Returns the string "Mesh".
  30743. */
  30744. Mesh.prototype.getClassName = function () {
  30745. return "Mesh";
  30746. };
  30747. /**
  30748. * Returns a string.
  30749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30750. */
  30751. Mesh.prototype.toString = function (fullDetails) {
  30752. var ret = _super.prototype.toString.call(this, fullDetails);
  30753. ret += ", n vertices: " + this.getTotalVertices();
  30754. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30755. if (this.animations) {
  30756. for (var i = 0; i < this.animations.length; i++) {
  30757. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30758. }
  30759. }
  30760. if (fullDetails) {
  30761. if (this._geometry) {
  30762. var ib = this.getIndices();
  30763. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30764. if (vb && ib) {
  30765. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30766. }
  30767. }
  30768. else {
  30769. ret += ", flat shading: UNKNOWN";
  30770. }
  30771. }
  30772. return ret;
  30773. };
  30774. Mesh.prototype._unBindEffect = function () {
  30775. _super.prototype._unBindEffect.call(this);
  30776. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30777. var instance = _a[_i];
  30778. instance._unBindEffect();
  30779. }
  30780. };
  30781. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30782. /**
  30783. * True if the mesh has some Levels Of Details (LOD).
  30784. * Returns a boolean.
  30785. */
  30786. get: function () {
  30787. return this._LODLevels.length > 0;
  30788. },
  30789. enumerable: true,
  30790. configurable: true
  30791. });
  30792. /**
  30793. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30794. * @returns an array of {BABYLON.MeshLODLevel}
  30795. */
  30796. Mesh.prototype.getLODLevels = function () {
  30797. return this._LODLevels;
  30798. };
  30799. Mesh.prototype._sortLODLevels = function () {
  30800. this._LODLevels.sort(function (a, b) {
  30801. if (a.distance < b.distance) {
  30802. return 1;
  30803. }
  30804. if (a.distance > b.distance) {
  30805. return -1;
  30806. }
  30807. return 0;
  30808. });
  30809. };
  30810. /**
  30811. * Add a mesh as LOD level triggered at the given distance.
  30812. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30813. * @param {number} distance The distance from the center of the object to show this level
  30814. * @param {Mesh} mesh The mesh to be added as LOD level
  30815. * @return {Mesh} This mesh (for chaining)
  30816. */
  30817. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30818. if (mesh && mesh._masterMesh) {
  30819. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30820. return this;
  30821. }
  30822. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30823. this._LODLevels.push(level);
  30824. if (mesh) {
  30825. mesh._masterMesh = this;
  30826. }
  30827. this._sortLODLevels();
  30828. return this;
  30829. };
  30830. /**
  30831. * Returns the LOD level mesh at the passed distance or null if not found.
  30832. * It is related to the method `addLODLevel(distance, mesh)`.
  30833. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30834. * Returns an object Mesh or `null`.
  30835. */
  30836. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30837. for (var index = 0; index < this._LODLevels.length; index++) {
  30838. var level = this._LODLevels[index];
  30839. if (level.distance === distance) {
  30840. return level.mesh;
  30841. }
  30842. }
  30843. return null;
  30844. };
  30845. /**
  30846. * Remove a mesh from the LOD array
  30847. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30848. * @param {Mesh} mesh The mesh to be removed.
  30849. * @return {Mesh} This mesh (for chaining)
  30850. */
  30851. Mesh.prototype.removeLODLevel = function (mesh) {
  30852. for (var index = 0; index < this._LODLevels.length; index++) {
  30853. if (this._LODLevels[index].mesh === mesh) {
  30854. this._LODLevels.splice(index, 1);
  30855. if (mesh) {
  30856. mesh._masterMesh = null;
  30857. }
  30858. }
  30859. }
  30860. this._sortLODLevels();
  30861. return this;
  30862. };
  30863. /**
  30864. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30865. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30866. */
  30867. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30868. if (!this._LODLevels || this._LODLevels.length === 0) {
  30869. return this;
  30870. }
  30871. var bSphere;
  30872. if (boundingSphere) {
  30873. bSphere = boundingSphere;
  30874. }
  30875. else {
  30876. var boundingInfo = this.getBoundingInfo();
  30877. bSphere = boundingInfo.boundingSphere;
  30878. }
  30879. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  30880. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  30881. if (this.onLODLevelSelection) {
  30882. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  30883. }
  30884. return this;
  30885. }
  30886. for (var index = 0; index < this._LODLevels.length; index++) {
  30887. var level = this._LODLevels[index];
  30888. if (level.distance < distanceToCamera) {
  30889. if (level.mesh) {
  30890. level.mesh._preActivate();
  30891. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  30892. }
  30893. if (this.onLODLevelSelection) {
  30894. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  30895. }
  30896. return level.mesh;
  30897. }
  30898. }
  30899. if (this.onLODLevelSelection) {
  30900. this.onLODLevelSelection(distanceToCamera, this, this);
  30901. }
  30902. return this;
  30903. };
  30904. Object.defineProperty(Mesh.prototype, "geometry", {
  30905. /**
  30906. * Returns the mesh internal Geometry object.
  30907. */
  30908. get: function () {
  30909. return this._geometry;
  30910. },
  30911. enumerable: true,
  30912. configurable: true
  30913. });
  30914. /**
  30915. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  30916. */
  30917. Mesh.prototype.getTotalVertices = function () {
  30918. if (this._geometry === null || this._geometry === undefined) {
  30919. return 0;
  30920. }
  30921. return this._geometry.getTotalVertices();
  30922. };
  30923. /**
  30924. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  30925. * 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.
  30926. * You can force the copy with forceCopy === true
  30927. * Returns null if the mesh has no geometry or no vertex buffer.
  30928. * Possible `kind` values :
  30929. * - BABYLON.VertexBuffer.PositionKind
  30930. * - BABYLON.VertexBuffer.UVKind
  30931. * - BABYLON.VertexBuffer.UV2Kind
  30932. * - BABYLON.VertexBuffer.UV3Kind
  30933. * - BABYLON.VertexBuffer.UV4Kind
  30934. * - BABYLON.VertexBuffer.UV5Kind
  30935. * - BABYLON.VertexBuffer.UV6Kind
  30936. * - BABYLON.VertexBuffer.ColorKind
  30937. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30938. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30939. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30940. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30941. */
  30942. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  30943. if (!this._geometry) {
  30944. return null;
  30945. }
  30946. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  30947. };
  30948. /**
  30949. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  30950. * Returns `null` if the mesh has no geometry.
  30951. * Possible `kind` values :
  30952. * - BABYLON.VertexBuffer.PositionKind
  30953. * - BABYLON.VertexBuffer.UVKind
  30954. * - BABYLON.VertexBuffer.UV2Kind
  30955. * - BABYLON.VertexBuffer.UV3Kind
  30956. * - BABYLON.VertexBuffer.UV4Kind
  30957. * - BABYLON.VertexBuffer.UV5Kind
  30958. * - BABYLON.VertexBuffer.UV6Kind
  30959. * - BABYLON.VertexBuffer.ColorKind
  30960. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30961. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30962. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30963. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30964. */
  30965. Mesh.prototype.getVertexBuffer = function (kind) {
  30966. if (!this._geometry) {
  30967. return null;
  30968. }
  30969. return this._geometry.getVertexBuffer(kind);
  30970. };
  30971. /**
  30972. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  30973. * Possible `kind` values :
  30974. * - BABYLON.VertexBuffer.PositionKind
  30975. * - BABYLON.VertexBuffer.UVKind
  30976. * - BABYLON.VertexBuffer.UV2Kind
  30977. * - BABYLON.VertexBuffer.UV3Kind
  30978. * - BABYLON.VertexBuffer.UV4Kind
  30979. * - BABYLON.VertexBuffer.UV5Kind
  30980. * - BABYLON.VertexBuffer.UV6Kind
  30981. * - BABYLON.VertexBuffer.ColorKind
  30982. * - BABYLON.VertexBuffer.MatricesIndicesKind
  30983. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  30984. * - BABYLON.VertexBuffer.MatricesWeightsKind
  30985. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  30986. */
  30987. Mesh.prototype.isVerticesDataPresent = function (kind) {
  30988. if (!this._geometry) {
  30989. if (this._delayInfo) {
  30990. return this._delayInfo.indexOf(kind) !== -1;
  30991. }
  30992. return false;
  30993. }
  30994. return this._geometry.isVerticesDataPresent(kind);
  30995. };
  30996. /**
  30997. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  30998. * Possible `kind` values :
  30999. * - BABYLON.VertexBuffer.PositionKind
  31000. * - BABYLON.VertexBuffer.UVKind
  31001. * - BABYLON.VertexBuffer.UV2Kind
  31002. * - BABYLON.VertexBuffer.UV3Kind
  31003. * - BABYLON.VertexBuffer.UV4Kind
  31004. * - BABYLON.VertexBuffer.UV5Kind
  31005. * - BABYLON.VertexBuffer.UV6Kind
  31006. * - BABYLON.VertexBuffer.ColorKind
  31007. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31008. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31009. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31010. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31011. */
  31012. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31013. if (!this._geometry) {
  31014. if (this._delayInfo) {
  31015. return this._delayInfo.indexOf(kind) !== -1;
  31016. }
  31017. return false;
  31018. }
  31019. return this._geometry.isVertexBufferUpdatable(kind);
  31020. };
  31021. /**
  31022. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31023. * Possible `kind` values :
  31024. * - BABYLON.VertexBuffer.PositionKind
  31025. * - BABYLON.VertexBuffer.UVKind
  31026. * - BABYLON.VertexBuffer.UV2Kind
  31027. * - BABYLON.VertexBuffer.UV3Kind
  31028. * - BABYLON.VertexBuffer.UV4Kind
  31029. * - BABYLON.VertexBuffer.UV5Kind
  31030. * - BABYLON.VertexBuffer.UV6Kind
  31031. * - BABYLON.VertexBuffer.ColorKind
  31032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31036. */
  31037. Mesh.prototype.getVerticesDataKinds = function () {
  31038. if (!this._geometry) {
  31039. var result = new Array();
  31040. if (this._delayInfo) {
  31041. this._delayInfo.forEach(function (kind, index, array) {
  31042. result.push(kind);
  31043. });
  31044. }
  31045. return result;
  31046. }
  31047. return this._geometry.getVerticesDataKinds();
  31048. };
  31049. /**
  31050. * Returns a positive integer : the total number of indices in this mesh geometry.
  31051. * Returns zero if the mesh has no geometry.
  31052. */
  31053. Mesh.prototype.getTotalIndices = function () {
  31054. if (!this._geometry) {
  31055. return 0;
  31056. }
  31057. return this._geometry.getTotalIndices();
  31058. };
  31059. /**
  31060. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31061. * 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.
  31062. * Returns an empty array if the mesh has no geometry.
  31063. */
  31064. Mesh.prototype.getIndices = function (copyWhenShared) {
  31065. if (!this._geometry) {
  31066. return [];
  31067. }
  31068. return this._geometry.getIndices(copyWhenShared);
  31069. };
  31070. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31071. get: function () {
  31072. return this._masterMesh !== null && this._masterMesh !== undefined;
  31073. },
  31074. enumerable: true,
  31075. configurable: true
  31076. });
  31077. /**
  31078. * Determine if the current mesh is ready to be rendered
  31079. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31080. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31081. * @returns true if all associated assets are ready (material, textures, shaders)
  31082. */
  31083. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31084. if (completeCheck === void 0) { completeCheck = false; }
  31085. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31086. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31087. return false;
  31088. }
  31089. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31090. return false;
  31091. }
  31092. if (!this.subMeshes || this.subMeshes.length === 0) {
  31093. return true;
  31094. }
  31095. if (!completeCheck) {
  31096. return true;
  31097. }
  31098. var engine = this.getEngine();
  31099. var scene = this.getScene();
  31100. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31101. this.computeWorldMatrix();
  31102. var mat = this.material || scene.defaultMaterial;
  31103. if (mat) {
  31104. if (mat.storeEffectOnSubMeshes) {
  31105. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31106. var subMesh = _a[_i];
  31107. var effectiveMaterial = subMesh.getMaterial();
  31108. if (effectiveMaterial) {
  31109. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31110. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31111. return false;
  31112. }
  31113. }
  31114. else {
  31115. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31116. return false;
  31117. }
  31118. }
  31119. }
  31120. }
  31121. }
  31122. else {
  31123. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31124. return false;
  31125. }
  31126. }
  31127. }
  31128. // Shadows
  31129. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31130. var light = _c[_b];
  31131. var generator = light.getShadowGenerator();
  31132. if (generator) {
  31133. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31134. var subMesh = _e[_d];
  31135. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31136. return false;
  31137. }
  31138. }
  31139. }
  31140. }
  31141. // LOD
  31142. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31143. var lod = _g[_f];
  31144. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31145. return false;
  31146. }
  31147. }
  31148. return true;
  31149. };
  31150. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31151. /**
  31152. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31153. * This property is pertinent only for updatable parametric shapes.
  31154. */
  31155. get: function () {
  31156. return this._areNormalsFrozen;
  31157. },
  31158. enumerable: true,
  31159. configurable: true
  31160. });
  31161. /**
  31162. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31163. * It has no effect at all on other shapes.
  31164. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31165. * Returns the Mesh.
  31166. */
  31167. Mesh.prototype.freezeNormals = function () {
  31168. this._areNormalsFrozen = true;
  31169. return this;
  31170. };
  31171. /**
  31172. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31173. * It has no effect at all on other shapes.
  31174. * It reactivates the mesh normals computation if it was previously frozen.
  31175. * Returns the Mesh.
  31176. */
  31177. Mesh.prototype.unfreezeNormals = function () {
  31178. this._areNormalsFrozen = false;
  31179. return this;
  31180. };
  31181. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31182. /**
  31183. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31184. */
  31185. set: function (count) {
  31186. this._overridenInstanceCount = count;
  31187. },
  31188. enumerable: true,
  31189. configurable: true
  31190. });
  31191. // Methods
  31192. Mesh.prototype._preActivate = function () {
  31193. var sceneRenderId = this.getScene().getRenderId();
  31194. if (this._preActivateId === sceneRenderId) {
  31195. return this;
  31196. }
  31197. this._preActivateId = sceneRenderId;
  31198. this._visibleInstances = null;
  31199. return this;
  31200. };
  31201. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31202. if (this._visibleInstances) {
  31203. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31204. }
  31205. return this;
  31206. };
  31207. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31208. if (!this._visibleInstances) {
  31209. this._visibleInstances = {};
  31210. this._visibleInstances.defaultRenderId = renderId;
  31211. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31212. }
  31213. if (!this._visibleInstances[renderId]) {
  31214. this._visibleInstances[renderId] = new Array();
  31215. }
  31216. this._visibleInstances[renderId].push(instance);
  31217. return this;
  31218. };
  31219. /**
  31220. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31221. * This means the mesh underlying bounding box and sphere are recomputed.
  31222. * Returns the Mesh.
  31223. */
  31224. Mesh.prototype.refreshBoundingInfo = function () {
  31225. return this._refreshBoundingInfo(false);
  31226. };
  31227. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31228. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31229. return this;
  31230. }
  31231. var data = this._getPositionData(applySkeleton);
  31232. if (data) {
  31233. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31234. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31235. }
  31236. if (this.subMeshes) {
  31237. for (var index = 0; index < this.subMeshes.length; index++) {
  31238. this.subMeshes[index].refreshBoundingInfo();
  31239. }
  31240. }
  31241. this._updateBoundingInfo();
  31242. return this;
  31243. };
  31244. Mesh.prototype._getPositionData = function (applySkeleton) {
  31245. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31246. if (data && applySkeleton && this.skeleton) {
  31247. data = BABYLON.Tools.Slice(data);
  31248. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31249. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31250. if (matricesWeightsData && matricesIndicesData) {
  31251. var needExtras = this.numBoneInfluencers > 4;
  31252. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31253. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31254. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31255. var tempVector = BABYLON.Tmp.Vector3[0];
  31256. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31257. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31258. var matWeightIdx = 0;
  31259. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31260. finalMatrix.reset();
  31261. var inf;
  31262. var weight;
  31263. for (inf = 0; inf < 4; inf++) {
  31264. weight = matricesWeightsData[matWeightIdx + inf];
  31265. if (weight <= 0)
  31266. break;
  31267. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31268. finalMatrix.addToSelf(tempMatrix);
  31269. }
  31270. if (needExtras) {
  31271. for (inf = 0; inf < 4; inf++) {
  31272. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31273. if (weight <= 0)
  31274. break;
  31275. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31276. finalMatrix.addToSelf(tempMatrix);
  31277. }
  31278. }
  31279. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31280. tempVector.toArray(data, index);
  31281. }
  31282. }
  31283. }
  31284. return data;
  31285. };
  31286. Mesh.prototype._createGlobalSubMesh = function (force) {
  31287. var totalVertices = this.getTotalVertices();
  31288. if (!totalVertices || !this.getIndices()) {
  31289. return null;
  31290. }
  31291. // Check if we need to recreate the submeshes
  31292. if (this.subMeshes && this.subMeshes.length > 0) {
  31293. var ib = this.getIndices();
  31294. if (!ib) {
  31295. return null;
  31296. }
  31297. var totalIndices = ib.length;
  31298. var needToRecreate = false;
  31299. if (force) {
  31300. needToRecreate = true;
  31301. }
  31302. else {
  31303. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31304. var submesh = _a[_i];
  31305. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31306. needToRecreate = true;
  31307. break;
  31308. }
  31309. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31310. needToRecreate = true;
  31311. break;
  31312. }
  31313. }
  31314. }
  31315. if (!needToRecreate) {
  31316. return this.subMeshes[0];
  31317. }
  31318. }
  31319. this.releaseSubMeshes();
  31320. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31321. };
  31322. Mesh.prototype.subdivide = function (count) {
  31323. if (count < 1) {
  31324. return;
  31325. }
  31326. var totalIndices = this.getTotalIndices();
  31327. var subdivisionSize = (totalIndices / count) | 0;
  31328. var offset = 0;
  31329. // Ensure that subdivisionSize is a multiple of 3
  31330. while (subdivisionSize % 3 !== 0) {
  31331. subdivisionSize++;
  31332. }
  31333. this.releaseSubMeshes();
  31334. for (var index = 0; index < count; index++) {
  31335. if (offset >= totalIndices) {
  31336. break;
  31337. }
  31338. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31339. offset += subdivisionSize;
  31340. }
  31341. this.synchronizeInstances();
  31342. };
  31343. /**
  31344. * Sets the vertex data of the mesh geometry for the requested `kind`.
  31345. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  31346. * The `data` are either a numeric array either a Float32Array.
  31347. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  31348. * 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).
  31349. * Note that a new underlying VertexBuffer object is created each call.
  31350. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  31351. *
  31352. * Possible `kind` values :
  31353. * - BABYLON.VertexBuffer.PositionKind
  31354. * - BABYLON.VertexBuffer.UVKind
  31355. * - BABYLON.VertexBuffer.UV2Kind
  31356. * - BABYLON.VertexBuffer.UV3Kind
  31357. * - BABYLON.VertexBuffer.UV4Kind
  31358. * - BABYLON.VertexBuffer.UV5Kind
  31359. * - BABYLON.VertexBuffer.UV6Kind
  31360. * - BABYLON.VertexBuffer.ColorKind
  31361. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31362. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31363. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31364. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31365. *
  31366. * Returns the Mesh.
  31367. */
  31368. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31369. if (updatable === void 0) { updatable = false; }
  31370. if (!this._geometry) {
  31371. var vertexData = new BABYLON.VertexData();
  31372. vertexData.set(data, kind);
  31373. var scene = this.getScene();
  31374. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31375. }
  31376. else {
  31377. this._geometry.setVerticesData(kind, data, updatable, stride);
  31378. }
  31379. return this;
  31380. };
  31381. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31382. if (updatable === void 0) { updatable = true; }
  31383. var vb = this.getVertexBuffer(kind);
  31384. if (!vb || vb.isUpdatable() === updatable) {
  31385. return;
  31386. }
  31387. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31388. };
  31389. /**
  31390. * Sets the mesh VertexBuffer.
  31391. * Returns the Mesh.
  31392. */
  31393. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31394. if (!this._geometry) {
  31395. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31396. }
  31397. this._geometry.setVerticesBuffer(buffer);
  31398. return this;
  31399. };
  31400. /**
  31401. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  31402. * If the mesh has no geometry, it is simply returned as it is.
  31403. * The `data` are either a numeric array either a Float32Array.
  31404. * No new underlying VertexBuffer object is created.
  31405. * 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.
  31406. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  31407. *
  31408. * Possible `kind` values :
  31409. * - BABYLON.VertexBuffer.PositionKind
  31410. * - BABYLON.VertexBuffer.UVKind
  31411. * - BABYLON.VertexBuffer.UV2Kind
  31412. * - BABYLON.VertexBuffer.UV3Kind
  31413. * - BABYLON.VertexBuffer.UV4Kind
  31414. * - BABYLON.VertexBuffer.UV5Kind
  31415. * - BABYLON.VertexBuffer.UV6Kind
  31416. * - BABYLON.VertexBuffer.ColorKind
  31417. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31418. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31419. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31420. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31421. *
  31422. * Returns the Mesh.
  31423. */
  31424. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31425. if (!this._geometry) {
  31426. return this;
  31427. }
  31428. if (!makeItUnique) {
  31429. this._geometry.updateVerticesData(kind, data, updateExtends);
  31430. }
  31431. else {
  31432. this.makeGeometryUnique();
  31433. this.updateVerticesData(kind, data, updateExtends, false);
  31434. }
  31435. return this;
  31436. };
  31437. /**
  31438. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31439. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31440. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31441. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31442. * Returns the Mesh.
  31443. */
  31444. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31445. if (computeNormals === void 0) { computeNormals = true; }
  31446. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31447. if (!positions) {
  31448. return this;
  31449. }
  31450. positionFunction(positions);
  31451. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31452. if (computeNormals) {
  31453. var indices = this.getIndices();
  31454. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31455. if (!normals) {
  31456. return this;
  31457. }
  31458. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31459. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31460. }
  31461. return this;
  31462. };
  31463. /**
  31464. * Creates a un-shared specific occurence of the geometry for the mesh.
  31465. * Returns the Mesh.
  31466. */
  31467. Mesh.prototype.makeGeometryUnique = function () {
  31468. if (!this._geometry) {
  31469. return this;
  31470. }
  31471. var oldGeometry = this._geometry;
  31472. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31473. oldGeometry.releaseForMesh(this, true);
  31474. geometry.applyToMesh(this);
  31475. return this;
  31476. };
  31477. /**
  31478. * Sets the mesh indices.
  31479. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  31480. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  31481. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  31482. * This method creates a new index buffer each call.
  31483. * Returns the Mesh.
  31484. */
  31485. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31486. if (totalVertices === void 0) { totalVertices = null; }
  31487. if (updatable === void 0) { updatable = false; }
  31488. if (!this._geometry) {
  31489. var vertexData = new BABYLON.VertexData();
  31490. vertexData.indices = indices;
  31491. var scene = this.getScene();
  31492. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31493. }
  31494. else {
  31495. this._geometry.setIndices(indices, totalVertices, updatable);
  31496. }
  31497. return this;
  31498. };
  31499. /**
  31500. * Update the current index buffer
  31501. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31502. * Returns the Mesh.
  31503. */
  31504. Mesh.prototype.updateIndices = function (indices, offset) {
  31505. if (!this._geometry) {
  31506. return this;
  31507. }
  31508. this._geometry.updateIndices(indices, offset);
  31509. return this;
  31510. };
  31511. /**
  31512. * Invert the geometry to move from a right handed system to a left handed one.
  31513. * Returns the Mesh.
  31514. */
  31515. Mesh.prototype.toLeftHanded = function () {
  31516. if (!this._geometry) {
  31517. return this;
  31518. }
  31519. this._geometry.toLeftHanded();
  31520. return this;
  31521. };
  31522. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31523. if (!this._geometry) {
  31524. return this;
  31525. }
  31526. var engine = this.getScene().getEngine();
  31527. // Wireframe
  31528. var indexToBind;
  31529. if (this._unIndexed) {
  31530. indexToBind = null;
  31531. }
  31532. else {
  31533. switch (fillMode) {
  31534. case BABYLON.Material.PointFillMode:
  31535. indexToBind = null;
  31536. break;
  31537. case BABYLON.Material.WireFrameFillMode:
  31538. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31539. break;
  31540. default:
  31541. case BABYLON.Material.TriangleFillMode:
  31542. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31543. break;
  31544. }
  31545. }
  31546. // VBOs
  31547. this._geometry._bind(effect, indexToBind);
  31548. return this;
  31549. };
  31550. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31551. if (alternate === void 0) { alternate = false; }
  31552. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31553. return this;
  31554. }
  31555. this.onBeforeDrawObservable.notifyObservers(this);
  31556. var scene = this.getScene();
  31557. var engine = scene.getEngine();
  31558. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31559. // or triangles as points
  31560. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31561. }
  31562. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31563. // Triangles as wireframe
  31564. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31565. }
  31566. else {
  31567. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31568. }
  31569. if (scene._isAlternateRenderingEnabled && !alternate) {
  31570. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31571. if (!effect || !scene.activeCamera) {
  31572. return this;
  31573. }
  31574. scene._switchToAlternateCameraConfiguration(true);
  31575. this._effectiveMaterial.bindView(effect);
  31576. this._effectiveMaterial.bindViewProjection(effect);
  31577. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31578. this._draw(subMesh, fillMode, instancesCount, true);
  31579. engine.setViewport(scene.activeCamera.viewport);
  31580. scene._switchToAlternateCameraConfiguration(false);
  31581. this._effectiveMaterial.bindView(effect);
  31582. this._effectiveMaterial.bindViewProjection(effect);
  31583. }
  31584. return this;
  31585. };
  31586. /**
  31587. * Registers for this mesh a javascript function called just before the rendering process.
  31588. * This function is passed the current mesh.
  31589. * Return the Mesh.
  31590. */
  31591. Mesh.prototype.registerBeforeRender = function (func) {
  31592. this.onBeforeRenderObservable.add(func);
  31593. return this;
  31594. };
  31595. /**
  31596. * Disposes a previously registered javascript function called before the rendering.
  31597. * This function is passed the current mesh.
  31598. * Returns the Mesh.
  31599. */
  31600. Mesh.prototype.unregisterBeforeRender = function (func) {
  31601. this.onBeforeRenderObservable.removeCallback(func);
  31602. return this;
  31603. };
  31604. /**
  31605. * Registers for this mesh a javascript function called just after the rendering is complete.
  31606. * This function is passed the current mesh.
  31607. * Returns the Mesh.
  31608. */
  31609. Mesh.prototype.registerAfterRender = function (func) {
  31610. this.onAfterRenderObservable.add(func);
  31611. return this;
  31612. };
  31613. /**
  31614. * Disposes a previously registered javascript function called after the rendering.
  31615. * This function is passed the current mesh.
  31616. * Return the Mesh.
  31617. */
  31618. Mesh.prototype.unregisterAfterRender = function (func) {
  31619. this.onAfterRenderObservable.removeCallback(func);
  31620. return this;
  31621. };
  31622. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31623. var scene = this.getScene();
  31624. this._batchCache.mustReturn = false;
  31625. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31626. this._batchCache.visibleInstances[subMeshId] = null;
  31627. if (this._visibleInstances) {
  31628. var currentRenderId = scene.getRenderId();
  31629. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31630. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31631. var selfRenderId = this._renderId;
  31632. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31633. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31634. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31635. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31636. }
  31637. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31638. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31639. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31640. this._batchCache.mustReturn = true;
  31641. return this._batchCache;
  31642. }
  31643. if (currentRenderId !== selfRenderId) {
  31644. this._batchCache.renderSelf[subMeshId] = false;
  31645. }
  31646. }
  31647. this._renderIdForInstances[subMeshId] = currentRenderId;
  31648. }
  31649. return this._batchCache;
  31650. };
  31651. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31652. var visibleInstances = batch.visibleInstances[subMesh._id];
  31653. if (!visibleInstances) {
  31654. return this;
  31655. }
  31656. var matricesCount = visibleInstances.length + 1;
  31657. var bufferSize = matricesCount * 16 * 4;
  31658. var currentInstancesBufferSize = this._instancesBufferSize;
  31659. var instancesBuffer = this._instancesBuffer;
  31660. while (this._instancesBufferSize < bufferSize) {
  31661. this._instancesBufferSize *= 2;
  31662. }
  31663. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31664. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31665. }
  31666. var offset = 0;
  31667. var instancesCount = 0;
  31668. var world = this.getWorldMatrix();
  31669. if (batch.renderSelf[subMesh._id]) {
  31670. world.copyToArray(this._instancesData, offset);
  31671. offset += 16;
  31672. instancesCount++;
  31673. }
  31674. if (visibleInstances) {
  31675. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31676. var instance = visibleInstances[instanceIndex];
  31677. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31678. offset += 16;
  31679. instancesCount++;
  31680. }
  31681. }
  31682. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31683. if (instancesBuffer) {
  31684. instancesBuffer.dispose();
  31685. }
  31686. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31687. this._instancesBuffer = instancesBuffer;
  31688. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31689. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31690. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31691. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31692. }
  31693. else {
  31694. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31695. }
  31696. this._bind(subMesh, effect, fillMode);
  31697. this._draw(subMesh, fillMode, instancesCount);
  31698. engine.unbindInstanceAttributes();
  31699. return this;
  31700. };
  31701. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31702. var scene = this.getScene();
  31703. var engine = scene.getEngine();
  31704. if (hardwareInstancedRendering) {
  31705. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31706. }
  31707. else {
  31708. if (batch.renderSelf[subMesh._id]) {
  31709. // Draw
  31710. if (onBeforeDraw) {
  31711. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31712. }
  31713. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31714. }
  31715. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31716. if (visibleInstancesForSubMesh) {
  31717. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31718. var instance = visibleInstancesForSubMesh[instanceIndex];
  31719. // World
  31720. var world = instance.getWorldMatrix();
  31721. if (onBeforeDraw) {
  31722. onBeforeDraw(true, world, effectiveMaterial);
  31723. }
  31724. // Draw
  31725. this._draw(subMesh, fillMode);
  31726. }
  31727. }
  31728. }
  31729. return this;
  31730. };
  31731. /**
  31732. * Triggers the draw call for the mesh.
  31733. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31734. * Returns the Mesh.
  31735. */
  31736. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31737. this.checkOcclusionQuery();
  31738. if (this._isOccluded) {
  31739. return this;
  31740. }
  31741. var scene = this.getScene();
  31742. // Managing instances
  31743. var batch = this._getInstancesRenderList(subMesh._id);
  31744. if (batch.mustReturn) {
  31745. return this;
  31746. }
  31747. // Checking geometry state
  31748. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31749. return this;
  31750. }
  31751. this.onBeforeRenderObservable.notifyObservers(this);
  31752. var engine = scene.getEngine();
  31753. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31754. // Material
  31755. var material = subMesh.getMaterial();
  31756. if (!material) {
  31757. return this;
  31758. }
  31759. this._effectiveMaterial = material;
  31760. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31761. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31762. return this;
  31763. }
  31764. }
  31765. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31766. return this;
  31767. }
  31768. // Alpha mode
  31769. if (enableAlphaMode) {
  31770. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31771. }
  31772. // Outline - step 1
  31773. var savedDepthWrite = engine.getDepthWrite();
  31774. if (this.renderOutline) {
  31775. engine.setDepthWrite(false);
  31776. scene.getOutlineRenderer().render(subMesh, batch);
  31777. engine.setDepthWrite(savedDepthWrite);
  31778. }
  31779. var effect;
  31780. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31781. effect = subMesh.effect;
  31782. }
  31783. else {
  31784. effect = this._effectiveMaterial.getEffect();
  31785. }
  31786. if (!effect) {
  31787. return this;
  31788. }
  31789. var sideOrientation = this.overrideMaterialSideOrientation;
  31790. if (sideOrientation == null) {
  31791. sideOrientation = this._effectiveMaterial.sideOrientation;
  31792. if (this._getWorldMatrixDeterminant() < 0) {
  31793. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31794. }
  31795. }
  31796. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31797. if (this._effectiveMaterial.forceDepthWrite) {
  31798. engine.setDepthWrite(true);
  31799. }
  31800. // Bind
  31801. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31802. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31803. this._bind(subMesh, effect, fillMode);
  31804. }
  31805. var world = this.getWorldMatrix();
  31806. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31807. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31808. }
  31809. else {
  31810. this._effectiveMaterial.bind(world, this);
  31811. }
  31812. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31813. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31814. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31815. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31816. }
  31817. // Draw
  31818. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31819. // Unbind
  31820. this._effectiveMaterial.unbind();
  31821. // Outline - step 2
  31822. if (this.renderOutline && savedDepthWrite) {
  31823. engine.setDepthWrite(true);
  31824. engine.setColorWrite(false);
  31825. scene.getOutlineRenderer().render(subMesh, batch);
  31826. engine.setColorWrite(true);
  31827. }
  31828. // Overlay
  31829. if (this.renderOverlay) {
  31830. var currentMode = engine.getAlphaMode();
  31831. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31832. scene.getOutlineRenderer().render(subMesh, batch, true);
  31833. engine.setAlphaMode(currentMode);
  31834. }
  31835. this.onAfterRenderObservable.notifyObservers(this);
  31836. return this;
  31837. };
  31838. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31839. if (isInstance && effectiveMaterial) {
  31840. effectiveMaterial.bindOnlyWorldMatrix(world);
  31841. }
  31842. };
  31843. /**
  31844. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31845. */
  31846. Mesh.prototype.getEmittedParticleSystems = function () {
  31847. var results = new Array();
  31848. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31849. var particleSystem = this.getScene().particleSystems[index];
  31850. if (particleSystem.emitter === this) {
  31851. results.push(particleSystem);
  31852. }
  31853. }
  31854. return results;
  31855. };
  31856. /**
  31857. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31858. */
  31859. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31860. var results = new Array();
  31861. var descendants = this.getDescendants();
  31862. descendants.push(this);
  31863. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31864. var particleSystem = this.getScene().particleSystems[index];
  31865. var emitter = particleSystem.emitter;
  31866. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31867. results.push(particleSystem);
  31868. }
  31869. }
  31870. return results;
  31871. };
  31872. Mesh.prototype._checkDelayState = function () {
  31873. var scene = this.getScene();
  31874. if (this._geometry) {
  31875. this._geometry.load(scene);
  31876. }
  31877. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31878. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31879. this._queueLoad(scene);
  31880. }
  31881. return this;
  31882. };
  31883. Mesh.prototype._queueLoad = function (scene) {
  31884. var _this = this;
  31885. scene._addPendingData(this);
  31886. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31887. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31888. if (data instanceof ArrayBuffer) {
  31889. _this._delayLoadingFunction(data, _this);
  31890. }
  31891. else {
  31892. _this._delayLoadingFunction(JSON.parse(data), _this);
  31893. }
  31894. _this.instances.forEach(function (instance) {
  31895. instance._syncSubMeshes();
  31896. });
  31897. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31898. scene._removePendingData(_this);
  31899. }, function () { }, scene.database, getBinaryData);
  31900. return this;
  31901. };
  31902. /**
  31903. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31904. */
  31905. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31906. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31907. return false;
  31908. }
  31909. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31910. return false;
  31911. }
  31912. this._checkDelayState();
  31913. return true;
  31914. };
  31915. /**
  31916. * Sets the mesh material by the material or multiMaterial `id` property.
  31917. * The material `id` is a string identifying the material or the multiMaterial.
  31918. * This method returns the Mesh.
  31919. */
  31920. Mesh.prototype.setMaterialByID = function (id) {
  31921. var materials = this.getScene().materials;
  31922. var index;
  31923. for (index = materials.length - 1; index > -1; index--) {
  31924. if (materials[index].id === id) {
  31925. this.material = materials[index];
  31926. return this;
  31927. }
  31928. }
  31929. // Multi
  31930. var multiMaterials = this.getScene().multiMaterials;
  31931. for (index = multiMaterials.length - 1; index > -1; index--) {
  31932. if (multiMaterials[index].id === id) {
  31933. this.material = multiMaterials[index];
  31934. return this;
  31935. }
  31936. }
  31937. return this;
  31938. };
  31939. /**
  31940. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31941. */
  31942. Mesh.prototype.getAnimatables = function () {
  31943. var results = new Array();
  31944. if (this.material) {
  31945. results.push(this.material);
  31946. }
  31947. if (this.skeleton) {
  31948. results.push(this.skeleton);
  31949. }
  31950. return results;
  31951. };
  31952. /**
  31953. * Modifies the mesh geometry according to the passed transformation matrix.
  31954. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  31955. * The mesh normals are modified accordingly the same transformation.
  31956. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  31957. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31958. * Returns the Mesh.
  31959. */
  31960. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  31961. // Position
  31962. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31963. return this;
  31964. }
  31965. var submeshes = this.subMeshes.splice(0);
  31966. this._resetPointsArrayCache();
  31967. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31968. var temp = new Array();
  31969. var index;
  31970. for (index = 0; index < data.length; index += 3) {
  31971. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  31972. }
  31973. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  31974. // Normals
  31975. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31976. return this;
  31977. }
  31978. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31979. temp = [];
  31980. for (index = 0; index < data.length; index += 3) {
  31981. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  31982. }
  31983. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  31984. // flip faces?
  31985. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  31986. this.flipFaces();
  31987. }
  31988. // Restore submeshes
  31989. this.releaseSubMeshes();
  31990. this.subMeshes = submeshes;
  31991. return this;
  31992. };
  31993. /**
  31994. * Modifies the mesh geometry according to its own current World Matrix.
  31995. * The mesh World Matrix is then reset.
  31996. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  31997. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  31998. * Note that, under the hood, this method sets a new VertexBuffer each call.
  31999. * Returns the Mesh.
  32000. */
  32001. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32002. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32003. this.scaling.copyFromFloats(1, 1, 1);
  32004. this.position.copyFromFloats(0, 0, 0);
  32005. this.rotation.copyFromFloats(0, 0, 0);
  32006. //only if quaternion is already set
  32007. if (this.rotationQuaternion) {
  32008. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32009. }
  32010. this._worldMatrix = BABYLON.Matrix.Identity();
  32011. return this;
  32012. };
  32013. Object.defineProperty(Mesh.prototype, "_positions", {
  32014. // Cache
  32015. get: function () {
  32016. if (this._geometry) {
  32017. return this._geometry._positions;
  32018. }
  32019. return null;
  32020. },
  32021. enumerable: true,
  32022. configurable: true
  32023. });
  32024. Mesh.prototype._resetPointsArrayCache = function () {
  32025. if (this._geometry) {
  32026. this._geometry._resetPointsArrayCache();
  32027. }
  32028. return this;
  32029. };
  32030. Mesh.prototype._generatePointsArray = function () {
  32031. if (this._geometry) {
  32032. return this._geometry._generatePointsArray();
  32033. }
  32034. return false;
  32035. };
  32036. /**
  32037. * Returns a new Mesh object generated from the current mesh properties.
  32038. * This method must not get confused with createInstance().
  32039. * The parameter `name` is a string, the name given to the new mesh.
  32040. * The optional parameter `newParent` can be any Node object (default `null`).
  32041. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32042. * 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.
  32043. */
  32044. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32045. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32046. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32047. };
  32048. /**
  32049. * Releases resources associated with this mesh.
  32050. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32051. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32052. */
  32053. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32054. var _this = this;
  32055. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32056. this.morphTargetManager = null;
  32057. if (this._geometry) {
  32058. this._geometry.releaseForMesh(this, true);
  32059. }
  32060. // Sources
  32061. var meshes = this.getScene().meshes;
  32062. meshes.forEach(function (abstractMesh) {
  32063. var mesh = abstractMesh;
  32064. if (mesh._source && mesh._source === _this) {
  32065. mesh._source = null;
  32066. }
  32067. });
  32068. this._source = null;
  32069. // Instances
  32070. if (this._instancesBuffer) {
  32071. this._instancesBuffer.dispose();
  32072. this._instancesBuffer = null;
  32073. }
  32074. while (this.instances.length) {
  32075. this.instances[0].dispose();
  32076. }
  32077. // Effect layers.
  32078. var effectLayers = this.getScene().effectLayers;
  32079. for (var i = 0; i < effectLayers.length; i++) {
  32080. var effectLayer = effectLayers[i];
  32081. if (effectLayer) {
  32082. effectLayer._disposeMesh(this);
  32083. }
  32084. }
  32085. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32086. };
  32087. /**
  32088. * Modifies the mesh geometry according to a displacement map.
  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 `url` is a string, the URL from the image file is to be downloaded.
  32093. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32094. * 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.
  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.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32101. var _this = this;
  32102. var scene = this.getScene();
  32103. var onload = function (img) {
  32104. // Getting height map data
  32105. var canvas = document.createElement("canvas");
  32106. var context = canvas.getContext("2d");
  32107. var heightMapWidth = img.width;
  32108. var heightMapHeight = img.height;
  32109. canvas.width = heightMapWidth;
  32110. canvas.height = heightMapHeight;
  32111. context.drawImage(img, 0, 0);
  32112. // Create VertexData from map data
  32113. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32114. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32115. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32116. //execute success callback, if set
  32117. if (onSuccess) {
  32118. onSuccess(_this);
  32119. }
  32120. };
  32121. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32122. return this;
  32123. };
  32124. /**
  32125. * Modifies the mesh geometry according to a displacementMap buffer.
  32126. * 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.
  32127. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32128. * This method returns nothing.
  32129. * 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.
  32130. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32131. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32132. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32133. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32134. *
  32135. * Returns the Mesh.
  32136. */
  32137. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32138. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32139. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32140. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32141. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32142. return this;
  32143. }
  32144. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32145. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32146. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32147. var position = BABYLON.Vector3.Zero();
  32148. var normal = BABYLON.Vector3.Zero();
  32149. var uv = BABYLON.Vector2.Zero();
  32150. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32151. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32152. for (var index = 0; index < positions.length; index += 3) {
  32153. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32154. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32155. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32156. // Compute height
  32157. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32158. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32159. var pos = (u + v * heightMapWidth) * 4;
  32160. var r = buffer[pos] / 255.0;
  32161. var g = buffer[pos + 1] / 255.0;
  32162. var b = buffer[pos + 2] / 255.0;
  32163. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32164. normal.normalize();
  32165. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32166. position = position.add(normal);
  32167. position.toArray(positions, index);
  32168. }
  32169. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32170. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32171. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32172. return this;
  32173. };
  32174. /**
  32175. * Modify the mesh to get a flat shading rendering.
  32176. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32177. * This method returns the Mesh.
  32178. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32179. */
  32180. Mesh.prototype.convertToFlatShadedMesh = function () {
  32181. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32182. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32183. var kinds = this.getVerticesDataKinds();
  32184. var vbs = {};
  32185. var data = {};
  32186. var newdata = {};
  32187. var updatableNormals = false;
  32188. var kindIndex;
  32189. var kind;
  32190. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32191. kind = kinds[kindIndex];
  32192. var vertexBuffer = this.getVertexBuffer(kind);
  32193. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32194. updatableNormals = vertexBuffer.isUpdatable();
  32195. kinds.splice(kindIndex, 1);
  32196. kindIndex--;
  32197. continue;
  32198. }
  32199. vbs[kind] = vertexBuffer;
  32200. data[kind] = vbs[kind].getData();
  32201. newdata[kind] = [];
  32202. }
  32203. // Save previous submeshes
  32204. var previousSubmeshes = this.subMeshes.slice(0);
  32205. var indices = this.getIndices();
  32206. var totalIndices = this.getTotalIndices();
  32207. // Generating unique vertices per face
  32208. var index;
  32209. for (index = 0; index < totalIndices; index++) {
  32210. var vertexIndex = indices[index];
  32211. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32212. kind = kinds[kindIndex];
  32213. var stride = vbs[kind].getStrideSize();
  32214. for (var offset = 0; offset < stride; offset++) {
  32215. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32216. }
  32217. }
  32218. }
  32219. // Updating faces & normal
  32220. var normals = [];
  32221. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32222. for (index = 0; index < totalIndices; index += 3) {
  32223. indices[index] = index;
  32224. indices[index + 1] = index + 1;
  32225. indices[index + 2] = index + 2;
  32226. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32227. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32228. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32229. var p1p2 = p1.subtract(p2);
  32230. var p3p2 = p3.subtract(p2);
  32231. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32232. // Store same normals for every vertex
  32233. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32234. normals.push(normal.x);
  32235. normals.push(normal.y);
  32236. normals.push(normal.z);
  32237. }
  32238. }
  32239. this.setIndices(indices);
  32240. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32241. // Updating vertex buffers
  32242. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32243. kind = kinds[kindIndex];
  32244. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32245. }
  32246. // Updating submeshes
  32247. this.releaseSubMeshes();
  32248. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32249. var previousOne = previousSubmeshes[submeshIndex];
  32250. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32251. }
  32252. this.synchronizeInstances();
  32253. return this;
  32254. };
  32255. /**
  32256. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32257. * In other words, more vertices, no more indices and a single bigger VBO.
  32258. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32259. * Returns the Mesh.
  32260. */
  32261. Mesh.prototype.convertToUnIndexedMesh = function () {
  32262. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32263. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32264. var kinds = this.getVerticesDataKinds();
  32265. var vbs = {};
  32266. var data = {};
  32267. var newdata = {};
  32268. var kindIndex;
  32269. var kind;
  32270. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32271. kind = kinds[kindIndex];
  32272. var vertexBuffer = this.getVertexBuffer(kind);
  32273. vbs[kind] = vertexBuffer;
  32274. data[kind] = vbs[kind].getData();
  32275. newdata[kind] = [];
  32276. }
  32277. // Save previous submeshes
  32278. var previousSubmeshes = this.subMeshes.slice(0);
  32279. var indices = this.getIndices();
  32280. var totalIndices = this.getTotalIndices();
  32281. // Generating unique vertices per face
  32282. var index;
  32283. for (index = 0; index < totalIndices; index++) {
  32284. var vertexIndex = indices[index];
  32285. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32286. kind = kinds[kindIndex];
  32287. var stride = vbs[kind].getStrideSize();
  32288. for (var offset = 0; offset < stride; offset++) {
  32289. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32290. }
  32291. }
  32292. }
  32293. // Updating indices
  32294. for (index = 0; index < totalIndices; index += 3) {
  32295. indices[index] = index;
  32296. indices[index + 1] = index + 1;
  32297. indices[index + 2] = index + 2;
  32298. }
  32299. this.setIndices(indices);
  32300. // Updating vertex buffers
  32301. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32302. kind = kinds[kindIndex];
  32303. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32304. }
  32305. // Updating submeshes
  32306. this.releaseSubMeshes();
  32307. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32308. var previousOne = previousSubmeshes[submeshIndex];
  32309. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32310. }
  32311. this._unIndexed = true;
  32312. this.synchronizeInstances();
  32313. return this;
  32314. };
  32315. /**
  32316. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32317. * This method returns the Mesh.
  32318. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32319. */
  32320. Mesh.prototype.flipFaces = function (flipNormals) {
  32321. if (flipNormals === void 0) { flipNormals = false; }
  32322. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32323. var i;
  32324. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32325. for (i = 0; i < vertex_data.normals.length; i++) {
  32326. vertex_data.normals[i] *= -1;
  32327. }
  32328. }
  32329. if (vertex_data.indices) {
  32330. var temp;
  32331. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32332. // reassign indices
  32333. temp = vertex_data.indices[i + 1];
  32334. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32335. vertex_data.indices[i + 2] = temp;
  32336. }
  32337. }
  32338. vertex_data.applyToMesh(this);
  32339. return this;
  32340. };
  32341. // Instances
  32342. /**
  32343. * Creates a new InstancedMesh object from the mesh model.
  32344. * An instance shares the same properties and the same material than its model.
  32345. * Only these properties of each instance can then be set individually :
  32346. * - position
  32347. * - rotation
  32348. * - rotationQuaternion
  32349. * - setPivotMatrix
  32350. * - scaling
  32351. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32352. * Warning : this method is not supported for Line mesh and LineSystem
  32353. */
  32354. Mesh.prototype.createInstance = function (name) {
  32355. return new BABYLON.InstancedMesh(name, this);
  32356. };
  32357. /**
  32358. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32359. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32360. * This method returns the Mesh.
  32361. */
  32362. Mesh.prototype.synchronizeInstances = function () {
  32363. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32364. var instance = this.instances[instanceIndex];
  32365. instance._syncSubMeshes();
  32366. }
  32367. return this;
  32368. };
  32369. /**
  32370. * Simplify the mesh according to the given array of settings.
  32371. * Function will return immediately and will simplify async. It returns the Mesh.
  32372. * @param settings a collection of simplification settings.
  32373. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32374. * @param type the type of simplification to run.
  32375. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32376. */
  32377. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32378. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32379. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32380. this.getScene().simplificationQueue.addTask({
  32381. settings: settings,
  32382. parallelProcessing: parallelProcessing,
  32383. mesh: this,
  32384. simplificationType: simplificationType,
  32385. successCallback: successCallback
  32386. });
  32387. return this;
  32388. };
  32389. /**
  32390. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32391. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32392. * This should be used together with the simplification to avoid disappearing triangles.
  32393. * Returns the Mesh.
  32394. * @param successCallback an optional success callback to be called after the optimization finished.
  32395. */
  32396. Mesh.prototype.optimizeIndices = function (successCallback) {
  32397. var _this = this;
  32398. var indices = this.getIndices();
  32399. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32400. if (!positions || !indices) {
  32401. return this;
  32402. }
  32403. var vectorPositions = new Array();
  32404. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32405. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32406. }
  32407. var dupes = new Array();
  32408. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32409. var realPos = vectorPositions.length - 1 - iteration;
  32410. var testedPosition = vectorPositions[realPos];
  32411. for (var j = 0; j < realPos; ++j) {
  32412. var againstPosition = vectorPositions[j];
  32413. if (testedPosition.equals(againstPosition)) {
  32414. dupes[realPos] = j;
  32415. break;
  32416. }
  32417. }
  32418. }, function () {
  32419. for (var i = 0; i < indices.length; ++i) {
  32420. indices[i] = dupes[indices[i]] || indices[i];
  32421. }
  32422. //indices are now reordered
  32423. var originalSubMeshes = _this.subMeshes.slice(0);
  32424. _this.setIndices(indices);
  32425. _this.subMeshes = originalSubMeshes;
  32426. if (successCallback) {
  32427. successCallback(_this);
  32428. }
  32429. });
  32430. return this;
  32431. };
  32432. Mesh.prototype.serialize = function (serializationObject) {
  32433. serializationObject.name = this.name;
  32434. serializationObject.id = this.id;
  32435. serializationObject.type = this.getClassName();
  32436. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32437. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32438. }
  32439. serializationObject.position = this.position.asArray();
  32440. if (this.rotationQuaternion) {
  32441. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32442. }
  32443. else if (this.rotation) {
  32444. serializationObject.rotation = this.rotation.asArray();
  32445. }
  32446. serializationObject.scaling = this.scaling.asArray();
  32447. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32448. serializationObject.isEnabled = this.isEnabled(false);
  32449. serializationObject.isVisible = this.isVisible;
  32450. serializationObject.infiniteDistance = this.infiniteDistance;
  32451. serializationObject.pickable = this.isPickable;
  32452. serializationObject.receiveShadows = this.receiveShadows;
  32453. serializationObject.billboardMode = this.billboardMode;
  32454. serializationObject.visibility = this.visibility;
  32455. serializationObject.checkCollisions = this.checkCollisions;
  32456. serializationObject.isBlocker = this.isBlocker;
  32457. // Parent
  32458. if (this.parent) {
  32459. serializationObject.parentId = this.parent.id;
  32460. }
  32461. // Geometry
  32462. serializationObject.isUnIndexed = this.isUnIndexed;
  32463. var geometry = this._geometry;
  32464. if (geometry) {
  32465. var geometryId = geometry.id;
  32466. serializationObject.geometryId = geometryId;
  32467. // SubMeshes
  32468. serializationObject.subMeshes = [];
  32469. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32470. var subMesh = this.subMeshes[subIndex];
  32471. serializationObject.subMeshes.push({
  32472. materialIndex: subMesh.materialIndex,
  32473. verticesStart: subMesh.verticesStart,
  32474. verticesCount: subMesh.verticesCount,
  32475. indexStart: subMesh.indexStart,
  32476. indexCount: subMesh.indexCount
  32477. });
  32478. }
  32479. }
  32480. // Material
  32481. if (this.material) {
  32482. serializationObject.materialId = this.material.id;
  32483. }
  32484. else {
  32485. this.material = null;
  32486. }
  32487. // Morph targets
  32488. if (this.morphTargetManager) {
  32489. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32490. }
  32491. // Skeleton
  32492. if (this.skeleton) {
  32493. serializationObject.skeletonId = this.skeleton.id;
  32494. }
  32495. // Physics
  32496. //TODO implement correct serialization for physics impostors.
  32497. var impostor = this.getPhysicsImpostor();
  32498. if (impostor) {
  32499. serializationObject.physicsMass = impostor.getParam("mass");
  32500. serializationObject.physicsFriction = impostor.getParam("friction");
  32501. serializationObject.physicsRestitution = impostor.getParam("mass");
  32502. serializationObject.physicsImpostor = impostor.type;
  32503. }
  32504. // Metadata
  32505. if (this.metadata) {
  32506. serializationObject.metadata = this.metadata;
  32507. }
  32508. // Instances
  32509. serializationObject.instances = [];
  32510. for (var index = 0; index < this.instances.length; index++) {
  32511. var instance = this.instances[index];
  32512. var serializationInstance = {
  32513. name: instance.name,
  32514. id: instance.id,
  32515. position: instance.position.asArray(),
  32516. scaling: instance.scaling.asArray()
  32517. };
  32518. if (instance.rotationQuaternion) {
  32519. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32520. }
  32521. else if (instance.rotation) {
  32522. serializationInstance.rotation = instance.rotation.asArray();
  32523. }
  32524. serializationObject.instances.push(serializationInstance);
  32525. // Animations
  32526. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32527. serializationInstance.ranges = instance.serializeAnimationRanges();
  32528. }
  32529. //
  32530. // Animations
  32531. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32532. serializationObject.ranges = this.serializeAnimationRanges();
  32533. // Layer mask
  32534. serializationObject.layerMask = this.layerMask;
  32535. // Alpha
  32536. serializationObject.alphaIndex = this.alphaIndex;
  32537. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32538. // Overlay
  32539. serializationObject.overlayAlpha = this.overlayAlpha;
  32540. serializationObject.overlayColor = this.overlayColor.asArray();
  32541. serializationObject.renderOverlay = this.renderOverlay;
  32542. // Fog
  32543. serializationObject.applyFog = this.applyFog;
  32544. // Action Manager
  32545. if (this.actionManager) {
  32546. serializationObject.actions = this.actionManager.serialize(this.name);
  32547. }
  32548. };
  32549. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32550. if (!this.geometry) {
  32551. return;
  32552. }
  32553. this._markSubMeshesAsAttributesDirty();
  32554. var morphTargetManager = this._morphTargetManager;
  32555. if (morphTargetManager && morphTargetManager.vertexCount) {
  32556. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32557. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32558. this.morphTargetManager = null;
  32559. return;
  32560. }
  32561. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32562. var morphTarget = morphTargetManager.getActiveTarget(index);
  32563. var positions = morphTarget.getPositions();
  32564. if (!positions) {
  32565. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32566. return;
  32567. }
  32568. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32569. var normals = morphTarget.getNormals();
  32570. if (normals) {
  32571. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32572. }
  32573. var tangents = morphTarget.getTangents();
  32574. if (tangents) {
  32575. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32576. }
  32577. }
  32578. }
  32579. else {
  32580. var index = 0;
  32581. // Positions
  32582. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32583. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32584. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32585. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32586. }
  32587. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32588. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32589. }
  32590. index++;
  32591. }
  32592. }
  32593. };
  32594. // Statics
  32595. /**
  32596. * Returns a new Mesh object parsed from the source provided.
  32597. * The parameter `parsedMesh` is the source.
  32598. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32599. */
  32600. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32601. var mesh;
  32602. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32603. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32604. }
  32605. else {
  32606. mesh = new Mesh(parsedMesh.name, scene);
  32607. }
  32608. mesh.id = parsedMesh.id;
  32609. if (BABYLON.Tags) {
  32610. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32611. }
  32612. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32613. if (parsedMesh.metadata !== undefined) {
  32614. mesh.metadata = parsedMesh.metadata;
  32615. }
  32616. if (parsedMesh.rotationQuaternion) {
  32617. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32618. }
  32619. else if (parsedMesh.rotation) {
  32620. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32621. }
  32622. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32623. if (parsedMesh.localMatrix) {
  32624. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32625. }
  32626. else if (parsedMesh.pivotMatrix) {
  32627. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32628. }
  32629. mesh.setEnabled(parsedMesh.isEnabled);
  32630. mesh.isVisible = parsedMesh.isVisible;
  32631. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32632. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32633. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32634. if (parsedMesh.applyFog !== undefined) {
  32635. mesh.applyFog = parsedMesh.applyFog;
  32636. }
  32637. if (parsedMesh.pickable !== undefined) {
  32638. mesh.isPickable = parsedMesh.pickable;
  32639. }
  32640. if (parsedMesh.alphaIndex !== undefined) {
  32641. mesh.alphaIndex = parsedMesh.alphaIndex;
  32642. }
  32643. mesh.receiveShadows = parsedMesh.receiveShadows;
  32644. mesh.billboardMode = parsedMesh.billboardMode;
  32645. if (parsedMesh.visibility !== undefined) {
  32646. mesh.visibility = parsedMesh.visibility;
  32647. }
  32648. mesh.checkCollisions = parsedMesh.checkCollisions;
  32649. if (parsedMesh.isBlocker !== undefined) {
  32650. mesh.isBlocker = parsedMesh.isBlocker;
  32651. }
  32652. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32653. // freezeWorldMatrix
  32654. if (parsedMesh.freezeWorldMatrix) {
  32655. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32656. }
  32657. // Parent
  32658. if (parsedMesh.parentId) {
  32659. mesh._waitingParentId = parsedMesh.parentId;
  32660. }
  32661. // Actions
  32662. if (parsedMesh.actions !== undefined) {
  32663. mesh._waitingActions = parsedMesh.actions;
  32664. }
  32665. // Overlay
  32666. if (parsedMesh.overlayAlpha !== undefined) {
  32667. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32668. }
  32669. if (parsedMesh.overlayColor !== undefined) {
  32670. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32671. }
  32672. if (parsedMesh.renderOverlay !== undefined) {
  32673. mesh.renderOverlay = parsedMesh.renderOverlay;
  32674. }
  32675. // Geometry
  32676. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32677. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32678. if (parsedMesh.delayLoadingFile) {
  32679. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32680. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32681. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32682. if (parsedMesh._binaryInfo) {
  32683. mesh._binaryInfo = parsedMesh._binaryInfo;
  32684. }
  32685. mesh._delayInfo = [];
  32686. if (parsedMesh.hasUVs) {
  32687. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32688. }
  32689. if (parsedMesh.hasUVs2) {
  32690. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32691. }
  32692. if (parsedMesh.hasUVs3) {
  32693. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32694. }
  32695. if (parsedMesh.hasUVs4) {
  32696. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32697. }
  32698. if (parsedMesh.hasUVs5) {
  32699. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32700. }
  32701. if (parsedMesh.hasUVs6) {
  32702. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32703. }
  32704. if (parsedMesh.hasColors) {
  32705. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32706. }
  32707. if (parsedMesh.hasMatricesIndices) {
  32708. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32709. }
  32710. if (parsedMesh.hasMatricesWeights) {
  32711. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32712. }
  32713. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32714. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32715. mesh._checkDelayState();
  32716. }
  32717. }
  32718. else {
  32719. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32720. }
  32721. // Material
  32722. if (parsedMesh.materialId) {
  32723. mesh.setMaterialByID(parsedMesh.materialId);
  32724. }
  32725. else {
  32726. mesh.material = null;
  32727. }
  32728. // Morph targets
  32729. if (parsedMesh.morphTargetManagerId > -1) {
  32730. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32731. }
  32732. // Skeleton
  32733. if (parsedMesh.skeletonId > -1) {
  32734. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32735. if (parsedMesh.numBoneInfluencers) {
  32736. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32737. }
  32738. }
  32739. // Animations
  32740. if (parsedMesh.animations) {
  32741. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32742. var parsedAnimation = parsedMesh.animations[animationIndex];
  32743. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32744. }
  32745. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32746. }
  32747. if (parsedMesh.autoAnimate) {
  32748. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32749. }
  32750. // Layer Mask
  32751. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32752. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32753. }
  32754. else {
  32755. mesh.layerMask = 0x0FFFFFFF;
  32756. }
  32757. // Physics
  32758. if (parsedMesh.physicsImpostor) {
  32759. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32760. mass: parsedMesh.physicsMass,
  32761. friction: parsedMesh.physicsFriction,
  32762. restitution: parsedMesh.physicsRestitution
  32763. }, scene);
  32764. }
  32765. // Instances
  32766. if (parsedMesh.instances) {
  32767. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32768. var parsedInstance = parsedMesh.instances[index];
  32769. var instance = mesh.createInstance(parsedInstance.name);
  32770. if (parsedInstance.id) {
  32771. instance.id = parsedInstance.id;
  32772. }
  32773. if (BABYLON.Tags) {
  32774. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32775. }
  32776. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32777. if (parsedInstance.parentId) {
  32778. instance._waitingParentId = parsedInstance.parentId;
  32779. }
  32780. if (parsedInstance.rotationQuaternion) {
  32781. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32782. }
  32783. else if (parsedInstance.rotation) {
  32784. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32785. }
  32786. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32787. instance.checkCollisions = mesh.checkCollisions;
  32788. if (parsedMesh.animations) {
  32789. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32790. parsedAnimation = parsedMesh.animations[animationIndex];
  32791. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32792. }
  32793. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32794. }
  32795. }
  32796. }
  32797. return mesh;
  32798. };
  32799. /**
  32800. * Creates a ribbon mesh.
  32801. * Please consider using the same method from the MeshBuilder class instead.
  32802. * 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.
  32803. *
  32804. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32805. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32806. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32807. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32808. * 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.
  32809. * 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.
  32810. * 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
  32811. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32812. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32813. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32814. */
  32815. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32816. if (closeArray === void 0) { closeArray = false; }
  32817. if (updatable === void 0) { updatable = false; }
  32818. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32819. pathArray: pathArray,
  32820. closeArray: closeArray,
  32821. closePath: closePath,
  32822. offset: offset,
  32823. updatable: updatable,
  32824. sideOrientation: sideOrientation,
  32825. instance: instance
  32826. }, scene);
  32827. };
  32828. /**
  32829. * Creates a plane polygonal mesh. By default, this is a disc.
  32830. * Please consider using the same method from the MeshBuilder class instead.
  32831. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32832. * 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.
  32833. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32834. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32835. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32836. */
  32837. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32838. if (scene === void 0) { scene = null; }
  32839. var options = {
  32840. radius: radius,
  32841. tessellation: tessellation,
  32842. sideOrientation: sideOrientation,
  32843. updatable: updatable
  32844. };
  32845. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32846. };
  32847. /**
  32848. * Creates a box mesh.
  32849. * Please consider using the same method from the MeshBuilder class instead.
  32850. * The parameter `size` sets the size (float) of each box side (default 1).
  32851. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32852. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32854. */
  32855. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32856. if (scene === void 0) { scene = null; }
  32857. var options = {
  32858. size: size,
  32859. sideOrientation: sideOrientation,
  32860. updatable: updatable
  32861. };
  32862. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32863. };
  32864. /**
  32865. * Creates a sphere mesh.
  32866. * Please consider using the same method from the MeshBuilder class instead.
  32867. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32868. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32872. */
  32873. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32874. var options = {
  32875. segments: segments,
  32876. diameterX: diameter,
  32877. diameterY: diameter,
  32878. diameterZ: diameter,
  32879. sideOrientation: sideOrientation,
  32880. updatable: updatable
  32881. };
  32882. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32883. };
  32884. /**
  32885. * Creates a cylinder or a cone mesh.
  32886. * Please consider using the same method from the MeshBuilder class instead.
  32887. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32888. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32889. * 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.
  32890. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32891. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32892. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32893. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32895. */
  32896. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32897. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32898. if (scene !== undefined) {
  32899. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32900. updatable = scene;
  32901. }
  32902. scene = subdivisions;
  32903. subdivisions = 1;
  32904. }
  32905. var options = {
  32906. height: height,
  32907. diameterTop: diameterTop,
  32908. diameterBottom: diameterBottom,
  32909. tessellation: tessellation,
  32910. subdivisions: subdivisions,
  32911. sideOrientation: sideOrientation,
  32912. updatable: updatable
  32913. };
  32914. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32915. };
  32916. // Torus (Code from SharpDX.org)
  32917. /**
  32918. * Creates a torus mesh.
  32919. * Please consider using the same method from the MeshBuilder class instead.
  32920. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32921. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32922. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32923. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32924. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32925. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32926. */
  32927. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32928. var options = {
  32929. diameter: diameter,
  32930. thickness: thickness,
  32931. tessellation: tessellation,
  32932. sideOrientation: sideOrientation,
  32933. updatable: updatable
  32934. };
  32935. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32936. };
  32937. /**
  32938. * Creates a torus knot mesh.
  32939. * Please consider using the same method from the MeshBuilder class instead.
  32940. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32941. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32942. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32943. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32947. */
  32948. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  32949. var options = {
  32950. radius: radius,
  32951. tube: tube,
  32952. radialSegments: radialSegments,
  32953. tubularSegments: tubularSegments,
  32954. p: p,
  32955. q: q,
  32956. sideOrientation: sideOrientation,
  32957. updatable: updatable
  32958. };
  32959. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  32960. };
  32961. /**
  32962. * Creates a line mesh.
  32963. * Please consider using the same method from the MeshBuilder class instead.
  32964. * 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.
  32965. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32966. * The parameter `points` is an array successive Vector3.
  32967. * 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
  32968. * When updating an instance, remember that only point positions can change, not the number of points.
  32969. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32970. */
  32971. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  32972. if (scene === void 0) { scene = null; }
  32973. if (updatable === void 0) { updatable = false; }
  32974. if (instance === void 0) { instance = null; }
  32975. var options = {
  32976. points: points,
  32977. updatable: updatable,
  32978. instance: instance
  32979. };
  32980. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  32981. };
  32982. /**
  32983. * Creates a dashed line mesh.
  32984. * Please consider using the same method from the MeshBuilder class instead.
  32985. * 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.
  32986. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  32987. * The parameter `points` is an array successive Vector3.
  32988. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  32989. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  32990. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  32991. * 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
  32992. * When updating an instance, remember that only point positions can change, not the number of points.
  32993. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32994. */
  32995. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  32996. if (scene === void 0) { scene = null; }
  32997. var options = {
  32998. points: points,
  32999. dashSize: dashSize,
  33000. gapSize: gapSize,
  33001. dashNb: dashNb,
  33002. updatable: updatable,
  33003. instance: instance
  33004. };
  33005. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33006. };
  33007. /**
  33008. * Creates a polygon mesh.
  33009. * Please consider using the same method from the MeshBuilder class instead.
  33010. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33011. * 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.
  33012. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33014. * Remember you can only change the shape positions, not their number when updating a polygon.
  33015. */
  33016. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33017. var options = {
  33018. shape: shape,
  33019. holes: holes,
  33020. updatable: updatable,
  33021. sideOrientation: sideOrientation
  33022. };
  33023. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33024. };
  33025. /**
  33026. * Creates an extruded polygon mesh, with depth in the Y direction.
  33027. * Please consider using the same method from the MeshBuilder class instead.
  33028. */
  33029. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33030. var options = {
  33031. shape: shape,
  33032. holes: holes,
  33033. depth: depth,
  33034. updatable: updatable,
  33035. sideOrientation: sideOrientation
  33036. };
  33037. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33038. };
  33039. /**
  33040. * Creates an extruded shape mesh.
  33041. * 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.
  33042. * Please consider using the same method from the MeshBuilder class instead.
  33043. *
  33044. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33045. * 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
  33046. * extruded along the Z axis.
  33047. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33048. * 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.
  33049. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33050. * 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
  33051. * 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
  33052. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33056. */
  33057. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33058. if (scene === void 0) { scene = null; }
  33059. var options = {
  33060. shape: shape,
  33061. path: path,
  33062. scale: scale,
  33063. rotation: rotation,
  33064. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33065. sideOrientation: sideOrientation,
  33066. instance: instance,
  33067. updatable: updatable
  33068. };
  33069. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33070. };
  33071. /**
  33072. * Creates an custom extruded shape mesh.
  33073. * 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.
  33074. * Please consider using the same method from the MeshBuilder class instead.
  33075. *
  33076. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33077. * 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
  33078. * extruded along the Z axis.
  33079. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33080. * 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
  33081. * and the distance of this point from the begining of the path :
  33082. * ```javascript
  33083. * var rotationFunction = function(i, distance) {
  33084. * // do things
  33085. * return rotationValue; }
  33086. * ```
  33087. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33088. * 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
  33089. * and the distance of this point from the begining of the path :
  33090. * ```javascript
  33091. * var scaleFunction = function(i, distance) {
  33092. * // do things
  33093. * return scaleValue;}
  33094. * ```
  33095. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33096. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33097. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33098. * 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
  33099. * 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
  33100. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33103. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33104. */
  33105. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33106. var options = {
  33107. shape: shape,
  33108. path: path,
  33109. scaleFunction: scaleFunction,
  33110. rotationFunction: rotationFunction,
  33111. ribbonCloseArray: ribbonCloseArray,
  33112. ribbonClosePath: ribbonClosePath,
  33113. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33114. sideOrientation: sideOrientation,
  33115. instance: instance,
  33116. updatable: updatable
  33117. };
  33118. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33119. };
  33120. /**
  33121. * Creates lathe mesh.
  33122. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33123. * Please consider using the same method from the MeshBuilder class instead.
  33124. * 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
  33125. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33126. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33127. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33128. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33129. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33130. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33131. */
  33132. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33133. var options = {
  33134. shape: shape,
  33135. radius: radius,
  33136. tessellation: tessellation,
  33137. sideOrientation: sideOrientation,
  33138. updatable: updatable
  33139. };
  33140. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33141. };
  33142. /**
  33143. * Creates a plane mesh.
  33144. * Please consider using the same method from the MeshBuilder class instead.
  33145. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33147. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  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.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33151. var options = {
  33152. size: size,
  33153. width: size,
  33154. height: size,
  33155. sideOrientation: sideOrientation,
  33156. updatable: updatable
  33157. };
  33158. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33159. };
  33160. /**
  33161. * Creates a ground mesh.
  33162. * Please consider using the same method from the MeshBuilder class instead.
  33163. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33164. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33166. */
  33167. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33168. var options = {
  33169. width: width,
  33170. height: height,
  33171. subdivisions: subdivisions,
  33172. updatable: updatable
  33173. };
  33174. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33175. };
  33176. /**
  33177. * Creates a tiled ground mesh.
  33178. * Please consider using the same method from the MeshBuilder class instead.
  33179. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33180. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33181. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33182. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33183. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33184. * numbers of subdivisions on the ground width and height of each tile.
  33185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33186. */
  33187. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33188. var options = {
  33189. xmin: xmin,
  33190. zmin: zmin,
  33191. xmax: xmax,
  33192. zmax: zmax,
  33193. subdivisions: subdivisions,
  33194. precision: precision,
  33195. updatable: updatable
  33196. };
  33197. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33198. };
  33199. /**
  33200. * Creates a ground mesh from a height map.
  33201. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33202. * Please consider using the same method from the MeshBuilder class instead.
  33203. * The parameter `url` sets the URL of the height map image resource.
  33204. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33205. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33206. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33207. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33208. * 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).
  33209. * This function is passed the newly built mesh :
  33210. * ```javascript
  33211. * function(mesh) { // do things
  33212. * return; }
  33213. * ```
  33214. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33215. */
  33216. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33217. var options = {
  33218. width: width,
  33219. height: height,
  33220. subdivisions: subdivisions,
  33221. minHeight: minHeight,
  33222. maxHeight: maxHeight,
  33223. updatable: updatable,
  33224. onReady: onReady
  33225. };
  33226. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33227. };
  33228. /**
  33229. * Creates a tube mesh.
  33230. * 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.
  33231. * Please consider using the same method from the MeshBuilder class instead.
  33232. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33233. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33234. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33235. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33236. * 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.
  33237. * It must return a radius value (positive float) :
  33238. * ```javascript
  33239. * var radiusFunction = function(i, distance) {
  33240. * // do things
  33241. * return radius; }
  33242. * ```
  33243. * 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
  33244. * 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
  33245. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33246. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33247. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33248. */
  33249. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33250. var options = {
  33251. path: path,
  33252. radius: radius,
  33253. tessellation: tessellation,
  33254. radiusFunction: radiusFunction,
  33255. arc: 1,
  33256. cap: cap,
  33257. updatable: updatable,
  33258. sideOrientation: sideOrientation,
  33259. instance: instance
  33260. };
  33261. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33262. };
  33263. /**
  33264. * Creates a polyhedron mesh.
  33265. * Please consider using the same method from the MeshBuilder class instead.
  33266. * 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
  33267. * to choose the wanted type.
  33268. * The parameter `size` (positive float, default 1) sets the polygon size.
  33269. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33270. * 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`.
  33271. * 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
  33272. * 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)`).
  33273. * 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
  33274. * 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.
  33275. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33276. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33277. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33278. */
  33279. Mesh.CreatePolyhedron = function (name, options, scene) {
  33280. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33281. };
  33282. /**
  33283. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33284. * Please consider using the same method from the MeshBuilder class instead.
  33285. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33286. * 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`).
  33287. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33288. * 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.
  33289. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33290. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33291. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33292. */
  33293. Mesh.CreateIcoSphere = function (name, options, scene) {
  33294. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33295. };
  33296. /**
  33297. * Creates a decal mesh.
  33298. * Please consider using the same method from the MeshBuilder class instead.
  33299. * 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.
  33300. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33301. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33302. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33303. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33304. */
  33305. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33306. var options = {
  33307. position: position,
  33308. normal: normal,
  33309. size: size,
  33310. angle: angle
  33311. };
  33312. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33313. };
  33314. // Skeletons
  33315. /**
  33316. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33317. */
  33318. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33319. if (!this._sourcePositions) {
  33320. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33321. if (!source) {
  33322. return this._sourcePositions;
  33323. }
  33324. this._sourcePositions = new Float32Array(source);
  33325. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33326. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33327. }
  33328. }
  33329. return this._sourcePositions;
  33330. };
  33331. /**
  33332. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33333. */
  33334. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33335. if (!this._sourceNormals) {
  33336. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33337. if (!source) {
  33338. return this._sourceNormals;
  33339. }
  33340. this._sourceNormals = new Float32Array(source);
  33341. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33342. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33343. }
  33344. }
  33345. return this._sourceNormals;
  33346. };
  33347. /**
  33348. * Updates the vertex buffer by applying transformation from the bones.
  33349. * Returns the Mesh.
  33350. *
  33351. * @param {skeleton} skeleton to apply
  33352. */
  33353. Mesh.prototype.applySkeleton = function (skeleton) {
  33354. if (!this.geometry) {
  33355. return this;
  33356. }
  33357. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33358. return this;
  33359. }
  33360. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33361. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33362. return this;
  33363. }
  33364. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33365. return this;
  33366. }
  33367. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33368. return this;
  33369. }
  33370. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33371. return this;
  33372. }
  33373. if (!this._sourcePositions) {
  33374. var submeshes = this.subMeshes.slice();
  33375. this.setPositionsForCPUSkinning();
  33376. this.subMeshes = submeshes;
  33377. }
  33378. if (!this._sourceNormals) {
  33379. this.setNormalsForCPUSkinning();
  33380. }
  33381. // positionsData checks for not being Float32Array will only pass at most once
  33382. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33383. if (!positionsData) {
  33384. return this;
  33385. }
  33386. if (!(positionsData instanceof Float32Array)) {
  33387. positionsData = new Float32Array(positionsData);
  33388. }
  33389. // normalsData checks for not being Float32Array will only pass at most once
  33390. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33391. if (!normalsData) {
  33392. return this;
  33393. }
  33394. if (!(normalsData instanceof Float32Array)) {
  33395. normalsData = new Float32Array(normalsData);
  33396. }
  33397. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33398. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33399. if (!matricesWeightsData || !matricesIndicesData) {
  33400. return this;
  33401. }
  33402. var needExtras = this.numBoneInfluencers > 4;
  33403. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33404. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33405. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33406. var tempVector3 = BABYLON.Vector3.Zero();
  33407. var finalMatrix = new BABYLON.Matrix();
  33408. var tempMatrix = new BABYLON.Matrix();
  33409. var matWeightIdx = 0;
  33410. var inf;
  33411. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33412. var weight;
  33413. for (inf = 0; inf < 4; inf++) {
  33414. weight = matricesWeightsData[matWeightIdx + inf];
  33415. if (weight > 0) {
  33416. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33417. finalMatrix.addToSelf(tempMatrix);
  33418. }
  33419. else
  33420. break;
  33421. }
  33422. if (needExtras) {
  33423. for (inf = 0; inf < 4; inf++) {
  33424. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33425. if (weight > 0) {
  33426. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33427. finalMatrix.addToSelf(tempMatrix);
  33428. }
  33429. else
  33430. break;
  33431. }
  33432. }
  33433. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33434. tempVector3.toArray(positionsData, index);
  33435. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33436. tempVector3.toArray(normalsData, index);
  33437. finalMatrix.reset();
  33438. }
  33439. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33440. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33441. return this;
  33442. };
  33443. // Tools
  33444. /**
  33445. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33446. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33447. */
  33448. Mesh.MinMax = function (meshes) {
  33449. var minVector = null;
  33450. var maxVector = null;
  33451. meshes.forEach(function (mesh, index, array) {
  33452. var boundingInfo = mesh.getBoundingInfo();
  33453. var boundingBox = boundingInfo.boundingBox;
  33454. if (!minVector || !maxVector) {
  33455. minVector = boundingBox.minimumWorld;
  33456. maxVector = boundingBox.maximumWorld;
  33457. }
  33458. else {
  33459. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33460. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33461. }
  33462. });
  33463. if (!minVector || !maxVector) {
  33464. return {
  33465. min: BABYLON.Vector3.Zero(),
  33466. max: BABYLON.Vector3.Zero()
  33467. };
  33468. }
  33469. return {
  33470. min: minVector,
  33471. max: maxVector
  33472. };
  33473. };
  33474. /**
  33475. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33476. */
  33477. Mesh.Center = function (meshesOrMinMaxVector) {
  33478. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33479. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33480. };
  33481. /**
  33482. * Merge the array of meshes into a single mesh for performance reasons.
  33483. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33484. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33485. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33486. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33487. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33488. */
  33489. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33490. if (disposeSource === void 0) { disposeSource = true; }
  33491. var index;
  33492. if (!allow32BitsIndices) {
  33493. var totalVertices = 0;
  33494. // Counting vertices
  33495. for (index = 0; index < meshes.length; index++) {
  33496. if (meshes[index]) {
  33497. totalVertices += meshes[index].getTotalVertices();
  33498. if (totalVertices > 65536) {
  33499. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33500. return null;
  33501. }
  33502. }
  33503. }
  33504. }
  33505. // Merge
  33506. var vertexData = null;
  33507. var otherVertexData;
  33508. var indiceArray = new Array();
  33509. var source = null;
  33510. for (index = 0; index < meshes.length; index++) {
  33511. if (meshes[index]) {
  33512. meshes[index].computeWorldMatrix(true);
  33513. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33514. otherVertexData.transform(meshes[index].getWorldMatrix());
  33515. if (vertexData) {
  33516. vertexData.merge(otherVertexData);
  33517. }
  33518. else {
  33519. vertexData = otherVertexData;
  33520. source = meshes[index];
  33521. }
  33522. if (subdivideWithSubMeshes) {
  33523. indiceArray.push(meshes[index].getTotalIndices());
  33524. }
  33525. }
  33526. }
  33527. source = source;
  33528. if (!meshSubclass) {
  33529. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33530. }
  33531. vertexData.applyToMesh(meshSubclass);
  33532. // Setting properties
  33533. meshSubclass.material = source.material;
  33534. meshSubclass.checkCollisions = source.checkCollisions;
  33535. // Cleaning
  33536. if (disposeSource) {
  33537. for (index = 0; index < meshes.length; index++) {
  33538. if (meshes[index]) {
  33539. meshes[index].dispose();
  33540. }
  33541. }
  33542. }
  33543. // Subdivide
  33544. if (subdivideWithSubMeshes) {
  33545. //-- Suppresions du submesh global
  33546. meshSubclass.releaseSubMeshes();
  33547. index = 0;
  33548. var offset = 0;
  33549. //-- aplique la subdivision en fonction du tableau d'indices
  33550. while (index < indiceArray.length) {
  33551. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33552. offset += indiceArray[index];
  33553. index++;
  33554. }
  33555. }
  33556. return meshSubclass;
  33557. };
  33558. // Consts
  33559. Mesh._FRONTSIDE = 0;
  33560. Mesh._BACKSIDE = 1;
  33561. Mesh._DOUBLESIDE = 2;
  33562. Mesh._DEFAULTSIDE = 0;
  33563. Mesh._NO_CAP = 0;
  33564. Mesh._CAP_START = 1;
  33565. Mesh._CAP_END = 2;
  33566. Mesh._CAP_ALL = 3;
  33567. return Mesh;
  33568. }(BABYLON.AbstractMesh));
  33569. BABYLON.Mesh = Mesh;
  33570. })(BABYLON || (BABYLON = {}));
  33571. //# sourceMappingURL=babylon.mesh.js.map
  33572. var BABYLON;
  33573. (function (BABYLON) {
  33574. var BaseSubMesh = /** @class */ (function () {
  33575. function BaseSubMesh() {
  33576. }
  33577. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33578. get: function () {
  33579. return this._materialEffect;
  33580. },
  33581. enumerable: true,
  33582. configurable: true
  33583. });
  33584. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33585. if (defines === void 0) { defines = null; }
  33586. if (this._materialEffect === effect) {
  33587. if (!effect) {
  33588. this._materialDefines = null;
  33589. }
  33590. return;
  33591. }
  33592. this._materialDefines = defines;
  33593. this._materialEffect = effect;
  33594. };
  33595. return BaseSubMesh;
  33596. }());
  33597. BABYLON.BaseSubMesh = BaseSubMesh;
  33598. var SubMesh = /** @class */ (function (_super) {
  33599. __extends(SubMesh, _super);
  33600. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33601. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33602. var _this = _super.call(this) || this;
  33603. _this.materialIndex = materialIndex;
  33604. _this.verticesStart = verticesStart;
  33605. _this.verticesCount = verticesCount;
  33606. _this.indexStart = indexStart;
  33607. _this.indexCount = indexCount;
  33608. _this._renderId = 0;
  33609. _this._mesh = mesh;
  33610. _this._renderingMesh = renderingMesh || mesh;
  33611. mesh.subMeshes.push(_this);
  33612. _this._trianglePlanes = [];
  33613. _this._id = mesh.subMeshes.length - 1;
  33614. if (createBoundingBox) {
  33615. _this.refreshBoundingInfo();
  33616. mesh.computeWorldMatrix(true);
  33617. }
  33618. return _this;
  33619. }
  33620. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33621. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33622. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33623. };
  33624. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33625. get: function () {
  33626. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33627. },
  33628. enumerable: true,
  33629. configurable: true
  33630. });
  33631. /**
  33632. * Returns the submesh BoudingInfo object.
  33633. */
  33634. SubMesh.prototype.getBoundingInfo = function () {
  33635. if (this.IsGlobal) {
  33636. return this._mesh.getBoundingInfo();
  33637. }
  33638. return this._boundingInfo;
  33639. };
  33640. /**
  33641. * Sets the submesh BoundingInfo.
  33642. * Return the SubMesh.
  33643. */
  33644. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33645. this._boundingInfo = boundingInfo;
  33646. return this;
  33647. };
  33648. /**
  33649. * Returns the mesh of the current submesh.
  33650. */
  33651. SubMesh.prototype.getMesh = function () {
  33652. return this._mesh;
  33653. };
  33654. /**
  33655. * Returns the rendering mesh of the submesh.
  33656. */
  33657. SubMesh.prototype.getRenderingMesh = function () {
  33658. return this._renderingMesh;
  33659. };
  33660. /**
  33661. * Returns the submesh material.
  33662. */
  33663. SubMesh.prototype.getMaterial = function () {
  33664. var rootMaterial = this._renderingMesh.material;
  33665. if (rootMaterial === null || rootMaterial === undefined) {
  33666. return this._mesh.getScene().defaultMaterial;
  33667. }
  33668. else if (rootMaterial.getSubMaterial) {
  33669. var multiMaterial = rootMaterial;
  33670. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33671. if (this._currentMaterial !== effectiveMaterial) {
  33672. this._currentMaterial = effectiveMaterial;
  33673. this._materialDefines = null;
  33674. }
  33675. return effectiveMaterial;
  33676. }
  33677. return rootMaterial;
  33678. };
  33679. // Methods
  33680. /**
  33681. * Sets a new updated BoundingInfo object to the submesh.
  33682. * Returns the SubMesh.
  33683. */
  33684. SubMesh.prototype.refreshBoundingInfo = function () {
  33685. this._lastColliderWorldVertices = null;
  33686. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33687. return this;
  33688. }
  33689. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33690. if (!data) {
  33691. this._boundingInfo = this._mesh.getBoundingInfo();
  33692. return this;
  33693. }
  33694. var indices = this._renderingMesh.getIndices();
  33695. var extend;
  33696. //is this the only submesh?
  33697. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33698. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33699. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33700. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33701. }
  33702. else {
  33703. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33704. }
  33705. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33706. return this;
  33707. };
  33708. SubMesh.prototype._checkCollision = function (collider) {
  33709. var boundingInfo = this.getBoundingInfo();
  33710. return boundingInfo._checkCollision(collider);
  33711. };
  33712. /**
  33713. * Updates the submesh BoundingInfo.
  33714. * Returns the Submesh.
  33715. */
  33716. SubMesh.prototype.updateBoundingInfo = function (world) {
  33717. var boundingInfo = this.getBoundingInfo();
  33718. if (!boundingInfo) {
  33719. this.refreshBoundingInfo();
  33720. boundingInfo = this.getBoundingInfo();
  33721. }
  33722. boundingInfo.update(world);
  33723. return this;
  33724. };
  33725. /**
  33726. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33727. * Boolean returned.
  33728. */
  33729. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33730. var boundingInfo = this.getBoundingInfo();
  33731. if (!boundingInfo) {
  33732. return false;
  33733. }
  33734. return boundingInfo.isInFrustum(frustumPlanes);
  33735. };
  33736. /**
  33737. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33738. * Boolean returned.
  33739. */
  33740. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33741. var boundingInfo = this.getBoundingInfo();
  33742. if (!boundingInfo) {
  33743. return false;
  33744. }
  33745. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33746. };
  33747. /**
  33748. * Renders the submesh.
  33749. * Returns it.
  33750. */
  33751. SubMesh.prototype.render = function (enableAlphaMode) {
  33752. this._renderingMesh.render(this, enableAlphaMode);
  33753. return this;
  33754. };
  33755. /**
  33756. * Returns a new Index Buffer.
  33757. * Type returned : WebGLBuffer.
  33758. */
  33759. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33760. if (!this._linesIndexBuffer) {
  33761. var linesIndices = [];
  33762. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33763. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33764. }
  33765. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33766. this.linesIndexCount = linesIndices.length;
  33767. }
  33768. return this._linesIndexBuffer;
  33769. };
  33770. /**
  33771. * True is the passed Ray intersects the submesh bounding box.
  33772. * Boolean returned.
  33773. */
  33774. SubMesh.prototype.canIntersects = function (ray) {
  33775. var boundingInfo = this.getBoundingInfo();
  33776. if (!boundingInfo) {
  33777. return false;
  33778. }
  33779. return ray.intersectsBox(boundingInfo.boundingBox);
  33780. };
  33781. /**
  33782. * Returns an object IntersectionInfo.
  33783. */
  33784. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33785. var intersectInfo = null;
  33786. var material = this.getMaterial();
  33787. if (!material) {
  33788. return null;
  33789. }
  33790. switch (material.fillMode) {
  33791. case BABYLON.Material.PointListDrawMode:
  33792. case BABYLON.Material.LineListDrawMode:
  33793. case BABYLON.Material.LineLoopDrawMode:
  33794. case BABYLON.Material.LineStripDrawMode:
  33795. case BABYLON.Material.TriangleFanDrawMode:
  33796. case BABYLON.Material.TriangleStripDrawMode:
  33797. return null;
  33798. }
  33799. // LineMesh first as it's also a Mesh...
  33800. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33801. var lineMesh = this._mesh;
  33802. // Line test
  33803. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33804. var p0 = positions[indices[index]];
  33805. var p1 = positions[indices[index + 1]];
  33806. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33807. if (length < 0) {
  33808. continue;
  33809. }
  33810. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33811. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33812. if (fastCheck) {
  33813. break;
  33814. }
  33815. }
  33816. }
  33817. }
  33818. else {
  33819. // Triangles test
  33820. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33821. var p0 = positions[indices[index]];
  33822. var p1 = positions[indices[index + 1]];
  33823. var p2 = positions[indices[index + 2]];
  33824. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33825. if (currentIntersectInfo) {
  33826. if (currentIntersectInfo.distance < 0) {
  33827. continue;
  33828. }
  33829. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33830. intersectInfo = currentIntersectInfo;
  33831. intersectInfo.faceId = index / 3;
  33832. if (fastCheck) {
  33833. break;
  33834. }
  33835. }
  33836. }
  33837. }
  33838. }
  33839. return intersectInfo;
  33840. };
  33841. SubMesh.prototype._rebuild = function () {
  33842. if (this._linesIndexBuffer) {
  33843. this._linesIndexBuffer = null;
  33844. }
  33845. };
  33846. // Clone
  33847. /**
  33848. * Creates a new Submesh from the passed Mesh.
  33849. */
  33850. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33851. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33852. if (!this.IsGlobal) {
  33853. var boundingInfo = this.getBoundingInfo();
  33854. if (!boundingInfo) {
  33855. return result;
  33856. }
  33857. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33858. }
  33859. return result;
  33860. };
  33861. // Dispose
  33862. /**
  33863. * Disposes the Submesh.
  33864. * Returns nothing.
  33865. */
  33866. SubMesh.prototype.dispose = function () {
  33867. if (this._linesIndexBuffer) {
  33868. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33869. this._linesIndexBuffer = null;
  33870. }
  33871. // Remove from mesh
  33872. var index = this._mesh.subMeshes.indexOf(this);
  33873. this._mesh.subMeshes.splice(index, 1);
  33874. };
  33875. // Statics
  33876. /**
  33877. * Creates a new Submesh from the passed parameters :
  33878. * - materialIndex (integer) : the index of the main mesh material.
  33879. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33880. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33881. * - mesh (Mesh) : the main mesh to create the submesh from.
  33882. * - renderingMesh (optional Mesh) : rendering mesh.
  33883. */
  33884. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33885. var minVertexIndex = Number.MAX_VALUE;
  33886. var maxVertexIndex = -Number.MAX_VALUE;
  33887. renderingMesh = (renderingMesh || mesh);
  33888. var indices = renderingMesh.getIndices();
  33889. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33890. var vertexIndex = indices[index];
  33891. if (vertexIndex < minVertexIndex)
  33892. minVertexIndex = vertexIndex;
  33893. if (vertexIndex > maxVertexIndex)
  33894. maxVertexIndex = vertexIndex;
  33895. }
  33896. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33897. };
  33898. return SubMesh;
  33899. }(BaseSubMesh));
  33900. BABYLON.SubMesh = SubMesh;
  33901. })(BABYLON || (BABYLON = {}));
  33902. //# sourceMappingURL=babylon.subMesh.js.map
  33903. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33904. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33905. s = arguments[i];
  33906. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33907. t[p] = s[p];
  33908. }
  33909. return t;
  33910. };
  33911. var BABYLON;
  33912. (function (BABYLON) {
  33913. /**
  33914. * Manages the defines for the Material
  33915. */
  33916. var MaterialDefines = /** @class */ (function () {
  33917. function MaterialDefines() {
  33918. this._isDirty = true;
  33919. /** @ignore */
  33920. this._areLightsDirty = true;
  33921. /** @ignore */
  33922. this._areAttributesDirty = true;
  33923. /** @ignore */
  33924. this._areTexturesDirty = true;
  33925. /** @ignore */
  33926. this._areFresnelDirty = true;
  33927. /** @ignore */
  33928. this._areMiscDirty = true;
  33929. /** @ignore */
  33930. this._areImageProcessingDirty = true;
  33931. /** @ignore */
  33932. this._normals = false;
  33933. /** @ignore */
  33934. this._uvs = false;
  33935. /** @ignore */
  33936. this._needNormals = false;
  33937. /** @ignore */
  33938. this._needUVs = false;
  33939. }
  33940. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33941. /**
  33942. * Specifies if the material needs to be re-calculated
  33943. */
  33944. get: function () {
  33945. return this._isDirty;
  33946. },
  33947. enumerable: true,
  33948. configurable: true
  33949. });
  33950. /**
  33951. * Marks the material to indicate that it has been re-calculated
  33952. */
  33953. MaterialDefines.prototype.markAsProcessed = function () {
  33954. this._isDirty = false;
  33955. this._areAttributesDirty = false;
  33956. this._areTexturesDirty = false;
  33957. this._areFresnelDirty = false;
  33958. this._areLightsDirty = false;
  33959. this._areMiscDirty = false;
  33960. this._areImageProcessingDirty = false;
  33961. };
  33962. /**
  33963. * Marks the material to indicate that it needs to be re-calculated
  33964. */
  33965. MaterialDefines.prototype.markAsUnprocessed = function () {
  33966. this._isDirty = true;
  33967. };
  33968. /**
  33969. * Marks the material to indicate all of its defines need to be re-calculated
  33970. */
  33971. MaterialDefines.prototype.markAllAsDirty = function () {
  33972. this._areTexturesDirty = true;
  33973. this._areAttributesDirty = true;
  33974. this._areLightsDirty = true;
  33975. this._areFresnelDirty = true;
  33976. this._areMiscDirty = true;
  33977. this._areImageProcessingDirty = true;
  33978. this._isDirty = true;
  33979. };
  33980. /**
  33981. * Marks the material to indicate that image processing needs to be re-calculated
  33982. */
  33983. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  33984. this._areImageProcessingDirty = true;
  33985. this._isDirty = true;
  33986. };
  33987. /**
  33988. * Marks the material to indicate the lights need to be re-calculated
  33989. */
  33990. MaterialDefines.prototype.markAsLightDirty = function () {
  33991. this._areLightsDirty = true;
  33992. this._isDirty = true;
  33993. };
  33994. /**
  33995. * Marks the attribute state as changed
  33996. */
  33997. MaterialDefines.prototype.markAsAttributesDirty = function () {
  33998. this._areAttributesDirty = true;
  33999. this._isDirty = true;
  34000. };
  34001. /**
  34002. * Marks the texture state as changed
  34003. */
  34004. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34005. this._areTexturesDirty = true;
  34006. this._isDirty = true;
  34007. };
  34008. /**
  34009. * Marks the fresnel state as changed
  34010. */
  34011. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34012. this._areFresnelDirty = true;
  34013. this._isDirty = true;
  34014. };
  34015. /**
  34016. * Marks the misc state as changed
  34017. */
  34018. MaterialDefines.prototype.markAsMiscDirty = function () {
  34019. this._areMiscDirty = true;
  34020. this._isDirty = true;
  34021. };
  34022. /**
  34023. * Rebuilds the material defines
  34024. */
  34025. MaterialDefines.prototype.rebuild = function () {
  34026. if (this._keys) {
  34027. delete this._keys;
  34028. }
  34029. this._keys = [];
  34030. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34031. var key = _a[_i];
  34032. if (key[0] === "_") {
  34033. continue;
  34034. }
  34035. this._keys.push(key);
  34036. }
  34037. };
  34038. /**
  34039. * Specifies if two material defines are equal
  34040. * @param other - A material define instance to compare to
  34041. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34042. */
  34043. MaterialDefines.prototype.isEqual = function (other) {
  34044. if (this._keys.length !== other._keys.length) {
  34045. return false;
  34046. }
  34047. for (var index = 0; index < this._keys.length; index++) {
  34048. var prop = this._keys[index];
  34049. if (this[prop] !== other[prop]) {
  34050. return false;
  34051. }
  34052. }
  34053. return true;
  34054. };
  34055. /**
  34056. * Clones this instance's defines to another instance
  34057. * @param other - material defines to clone values to
  34058. */
  34059. MaterialDefines.prototype.cloneTo = function (other) {
  34060. if (this._keys.length !== other._keys.length) {
  34061. other._keys = this._keys.slice(0);
  34062. }
  34063. for (var index = 0; index < this._keys.length; index++) {
  34064. var prop = this._keys[index];
  34065. other[prop] = this[prop];
  34066. }
  34067. };
  34068. /**
  34069. * Resets the material define values
  34070. */
  34071. MaterialDefines.prototype.reset = function () {
  34072. for (var index = 0; index < this._keys.length; index++) {
  34073. var prop = this._keys[index];
  34074. var type = typeof this[prop];
  34075. switch (type) {
  34076. case "number":
  34077. this[prop] = 0;
  34078. break;
  34079. case "string":
  34080. this[prop] = "";
  34081. break;
  34082. default:
  34083. this[prop] = false;
  34084. break;
  34085. }
  34086. }
  34087. };
  34088. /**
  34089. * Converts the material define values to a string
  34090. * @returns - String of material define information
  34091. */
  34092. MaterialDefines.prototype.toString = function () {
  34093. var result = "";
  34094. for (var index = 0; index < this._keys.length; index++) {
  34095. var prop = this._keys[index];
  34096. var value = this[prop];
  34097. var type = typeof value;
  34098. switch (type) {
  34099. case "number":
  34100. case "string":
  34101. result += "#define " + prop + " " + value + "\n";
  34102. break;
  34103. default:
  34104. if (value) {
  34105. result += "#define " + prop + "\n";
  34106. }
  34107. break;
  34108. }
  34109. }
  34110. return result;
  34111. };
  34112. return MaterialDefines;
  34113. }());
  34114. BABYLON.MaterialDefines = MaterialDefines;
  34115. /**
  34116. * Base class for the main features of a material in Babylon.js
  34117. */
  34118. var Material = /** @class */ (function () {
  34119. /**
  34120. * Creates a material instance
  34121. * @param name defines the name of the material
  34122. * @param scene defines the scene to reference
  34123. * @param doNotAdd specifies if the material should be added to the scene
  34124. */
  34125. function Material(name, scene, doNotAdd) {
  34126. /**
  34127. * Specifies if the ready state should be checked on each call
  34128. */
  34129. this.checkReadyOnEveryCall = false;
  34130. /**
  34131. * Specifies if the ready state should be checked once
  34132. */
  34133. this.checkReadyOnlyOnce = false;
  34134. /**
  34135. * The state of the material
  34136. */
  34137. this.state = "";
  34138. /**
  34139. * The alpha value of the material
  34140. */
  34141. this._alpha = 1.0;
  34142. /**
  34143. * Specifies if back face culling is enabled
  34144. */
  34145. this._backFaceCulling = true;
  34146. /**
  34147. * Specifies if the material should be serialized
  34148. */
  34149. this.doNotSerialize = false;
  34150. /**
  34151. * Specifies if the effect should be stored on sub meshes
  34152. */
  34153. this.storeEffectOnSubMeshes = false;
  34154. /**
  34155. * An event triggered when the material is disposed
  34156. */
  34157. this.onDisposeObservable = new BABYLON.Observable();
  34158. /**
  34159. * An event triggered when the material is bound
  34160. */
  34161. this.onBindObservable = new BABYLON.Observable();
  34162. /**
  34163. * An event triggered when the material is unbound
  34164. */
  34165. this.onUnBindObservable = new BABYLON.Observable();
  34166. /**
  34167. * Stores the value of the alpha mode
  34168. */
  34169. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34170. /**
  34171. * Stores the state of the need depth pre-pass value
  34172. */
  34173. this._needDepthPrePass = false;
  34174. /**
  34175. * Specifies if depth writing should be disabled
  34176. */
  34177. this.disableDepthWrite = false;
  34178. /**
  34179. * Specifies if depth writing should be forced
  34180. */
  34181. this.forceDepthWrite = false;
  34182. /**
  34183. * Specifies if there should be a separate pass for culling
  34184. */
  34185. this.separateCullingPass = false;
  34186. /**
  34187. * Stores the state specifing if fog should be enabled
  34188. */
  34189. this._fogEnabled = true;
  34190. /**
  34191. * Stores the size of points
  34192. */
  34193. this.pointSize = 1.0;
  34194. /**
  34195. * Stores the z offset value
  34196. */
  34197. this.zOffset = 0;
  34198. /**
  34199. * Specifies if the material was previously ready
  34200. */
  34201. this._wasPreviouslyReady = false;
  34202. /**
  34203. * Stores the fill mode state
  34204. */
  34205. this._fillMode = Material.TriangleFillMode;
  34206. this.name = name;
  34207. this.id = name || BABYLON.Tools.RandomId();
  34208. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34209. if (this._scene.useRightHandedSystem) {
  34210. this.sideOrientation = Material.ClockWiseSideOrientation;
  34211. }
  34212. else {
  34213. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34214. }
  34215. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34216. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34217. if (!doNotAdd) {
  34218. this._scene.materials.push(this);
  34219. }
  34220. }
  34221. Object.defineProperty(Material, "TriangleFillMode", {
  34222. /**
  34223. * Returns the triangle fill mode
  34224. */
  34225. get: function () {
  34226. return Material._TriangleFillMode;
  34227. },
  34228. enumerable: true,
  34229. configurable: true
  34230. });
  34231. Object.defineProperty(Material, "WireFrameFillMode", {
  34232. /**
  34233. * Returns the wireframe mode
  34234. */
  34235. get: function () {
  34236. return Material._WireFrameFillMode;
  34237. },
  34238. enumerable: true,
  34239. configurable: true
  34240. });
  34241. Object.defineProperty(Material, "PointFillMode", {
  34242. /**
  34243. * Returns the point fill mode
  34244. */
  34245. get: function () {
  34246. return Material._PointFillMode;
  34247. },
  34248. enumerable: true,
  34249. configurable: true
  34250. });
  34251. Object.defineProperty(Material, "PointListDrawMode", {
  34252. /**
  34253. * Returns the point list draw mode
  34254. */
  34255. get: function () {
  34256. return Material._PointListDrawMode;
  34257. },
  34258. enumerable: true,
  34259. configurable: true
  34260. });
  34261. Object.defineProperty(Material, "LineListDrawMode", {
  34262. /**
  34263. * Returns the line list draw mode
  34264. */
  34265. get: function () {
  34266. return Material._LineListDrawMode;
  34267. },
  34268. enumerable: true,
  34269. configurable: true
  34270. });
  34271. Object.defineProperty(Material, "LineLoopDrawMode", {
  34272. /**
  34273. * Returns the line loop draw mode
  34274. */
  34275. get: function () {
  34276. return Material._LineLoopDrawMode;
  34277. },
  34278. enumerable: true,
  34279. configurable: true
  34280. });
  34281. Object.defineProperty(Material, "LineStripDrawMode", {
  34282. /**
  34283. * Returns the line strip draw mode
  34284. */
  34285. get: function () {
  34286. return Material._LineStripDrawMode;
  34287. },
  34288. enumerable: true,
  34289. configurable: true
  34290. });
  34291. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34292. /**
  34293. * Returns the triangle strip draw mode
  34294. */
  34295. get: function () {
  34296. return Material._TriangleStripDrawMode;
  34297. },
  34298. enumerable: true,
  34299. configurable: true
  34300. });
  34301. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34302. /**
  34303. * Returns the triangle fan draw mode
  34304. */
  34305. get: function () {
  34306. return Material._TriangleFanDrawMode;
  34307. },
  34308. enumerable: true,
  34309. configurable: true
  34310. });
  34311. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34312. /**
  34313. * Returns the clock-wise side orientation
  34314. */
  34315. get: function () {
  34316. return Material._ClockWiseSideOrientation;
  34317. },
  34318. enumerable: true,
  34319. configurable: true
  34320. });
  34321. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34322. /**
  34323. * Returns the counter clock-wise side orientation
  34324. */
  34325. get: function () {
  34326. return Material._CounterClockWiseSideOrientation;
  34327. },
  34328. enumerable: true,
  34329. configurable: true
  34330. });
  34331. Object.defineProperty(Material, "TextureDirtyFlag", {
  34332. /**
  34333. * Returns the dirty texture flag value
  34334. */
  34335. get: function () {
  34336. return Material._TextureDirtyFlag;
  34337. },
  34338. enumerable: true,
  34339. configurable: true
  34340. });
  34341. Object.defineProperty(Material, "LightDirtyFlag", {
  34342. /**
  34343. * Returns the dirty light flag value
  34344. */
  34345. get: function () {
  34346. return Material._LightDirtyFlag;
  34347. },
  34348. enumerable: true,
  34349. configurable: true
  34350. });
  34351. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34352. /**
  34353. * Returns the dirty fresnel flag value
  34354. */
  34355. get: function () {
  34356. return Material._FresnelDirtyFlag;
  34357. },
  34358. enumerable: true,
  34359. configurable: true
  34360. });
  34361. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34362. /**
  34363. * Returns the dirty attributes flag value
  34364. */
  34365. get: function () {
  34366. return Material._AttributesDirtyFlag;
  34367. },
  34368. enumerable: true,
  34369. configurable: true
  34370. });
  34371. Object.defineProperty(Material, "MiscDirtyFlag", {
  34372. /**
  34373. * Returns the dirty misc flag value
  34374. */
  34375. get: function () {
  34376. return Material._MiscDirtyFlag;
  34377. },
  34378. enumerable: true,
  34379. configurable: true
  34380. });
  34381. Object.defineProperty(Material.prototype, "alpha", {
  34382. /**
  34383. * Gets the alpha value of the material
  34384. */
  34385. get: function () {
  34386. return this._alpha;
  34387. },
  34388. /**
  34389. * Sets the alpha value of the material
  34390. */
  34391. set: function (value) {
  34392. if (this._alpha === value) {
  34393. return;
  34394. }
  34395. this._alpha = value;
  34396. this.markAsDirty(Material.MiscDirtyFlag);
  34397. },
  34398. enumerable: true,
  34399. configurable: true
  34400. });
  34401. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34402. /**
  34403. * Gets the back-face culling state
  34404. */
  34405. get: function () {
  34406. return this._backFaceCulling;
  34407. },
  34408. /**
  34409. * Sets the back-face culling state
  34410. */
  34411. set: function (value) {
  34412. if (this._backFaceCulling === value) {
  34413. return;
  34414. }
  34415. this._backFaceCulling = value;
  34416. this.markAsDirty(Material.TextureDirtyFlag);
  34417. },
  34418. enumerable: true,
  34419. configurable: true
  34420. });
  34421. Object.defineProperty(Material.prototype, "onDispose", {
  34422. /**
  34423. * Called during a dispose event
  34424. */
  34425. set: function (callback) {
  34426. if (this._onDisposeObserver) {
  34427. this.onDisposeObservable.remove(this._onDisposeObserver);
  34428. }
  34429. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34430. },
  34431. enumerable: true,
  34432. configurable: true
  34433. });
  34434. Object.defineProperty(Material.prototype, "onBind", {
  34435. /**
  34436. * Called during a bind event
  34437. */
  34438. set: function (callback) {
  34439. if (this._onBindObserver) {
  34440. this.onBindObservable.remove(this._onBindObserver);
  34441. }
  34442. this._onBindObserver = this.onBindObservable.add(callback);
  34443. },
  34444. enumerable: true,
  34445. configurable: true
  34446. });
  34447. Object.defineProperty(Material.prototype, "alphaMode", {
  34448. /**
  34449. * Gets the value of the alpha mode
  34450. */
  34451. get: function () {
  34452. return this._alphaMode;
  34453. },
  34454. /**
  34455. * Sets the value of the alpha mode.
  34456. *
  34457. * | Value | Type | Description |
  34458. * | --- | --- | --- |
  34459. * | 0 | ALPHA_DISABLE | |
  34460. * | 1 | ALPHA_ADD | |
  34461. * | 2 | ALPHA_COMBINE | |
  34462. * | 3 | ALPHA_SUBTRACT | |
  34463. * | 4 | ALPHA_MULTIPLY | |
  34464. * | 5 | ALPHA_MAXIMIZED | |
  34465. * | 6 | ALPHA_ONEONE | |
  34466. * | 7 | ALPHA_PREMULTIPLIED | |
  34467. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34468. * | 9 | ALPHA_INTERPOLATE | |
  34469. * | 10 | ALPHA_SCREENMODE | |
  34470. *
  34471. */
  34472. set: function (value) {
  34473. if (this._alphaMode === value) {
  34474. return;
  34475. }
  34476. this._alphaMode = value;
  34477. this.markAsDirty(Material.TextureDirtyFlag);
  34478. },
  34479. enumerable: true,
  34480. configurable: true
  34481. });
  34482. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34483. /**
  34484. * Gets the depth pre-pass value
  34485. */
  34486. get: function () {
  34487. return this._needDepthPrePass;
  34488. },
  34489. /**
  34490. * Sets the need depth pre-pass value
  34491. */
  34492. set: function (value) {
  34493. if (this._needDepthPrePass === value) {
  34494. return;
  34495. }
  34496. this._needDepthPrePass = value;
  34497. if (this._needDepthPrePass) {
  34498. this.checkReadyOnEveryCall = true;
  34499. }
  34500. },
  34501. enumerable: true,
  34502. configurable: true
  34503. });
  34504. Object.defineProperty(Material.prototype, "fogEnabled", {
  34505. /**
  34506. * Gets the value of the fog enabled state
  34507. */
  34508. get: function () {
  34509. return this._fogEnabled;
  34510. },
  34511. /**
  34512. * Sets the state for enabling fog
  34513. */
  34514. set: function (value) {
  34515. if (this._fogEnabled === value) {
  34516. return;
  34517. }
  34518. this._fogEnabled = value;
  34519. this.markAsDirty(Material.MiscDirtyFlag);
  34520. },
  34521. enumerable: true,
  34522. configurable: true
  34523. });
  34524. Object.defineProperty(Material.prototype, "wireframe", {
  34525. /**
  34526. * Gets a value specifying if wireframe mode is enabled
  34527. */
  34528. get: function () {
  34529. switch (this._fillMode) {
  34530. case Material.WireFrameFillMode:
  34531. case Material.LineListDrawMode:
  34532. case Material.LineLoopDrawMode:
  34533. case Material.LineStripDrawMode:
  34534. return true;
  34535. }
  34536. return this._scene.forceWireframe;
  34537. },
  34538. /**
  34539. * Sets the state of wireframe mode
  34540. */
  34541. set: function (value) {
  34542. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34543. },
  34544. enumerable: true,
  34545. configurable: true
  34546. });
  34547. Object.defineProperty(Material.prototype, "pointsCloud", {
  34548. /**
  34549. * Gets the value specifying if point clouds are enabled
  34550. */
  34551. get: function () {
  34552. switch (this._fillMode) {
  34553. case Material.PointFillMode:
  34554. case Material.PointListDrawMode:
  34555. return true;
  34556. }
  34557. return this._scene.forcePointsCloud;
  34558. },
  34559. /**
  34560. * Sets the state of point cloud mode
  34561. */
  34562. set: function (value) {
  34563. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34564. },
  34565. enumerable: true,
  34566. configurable: true
  34567. });
  34568. Object.defineProperty(Material.prototype, "fillMode", {
  34569. /**
  34570. * Gets the material fill mode
  34571. */
  34572. get: function () {
  34573. return this._fillMode;
  34574. },
  34575. /**
  34576. * Sets the material fill mode
  34577. */
  34578. set: function (value) {
  34579. if (this._fillMode === value) {
  34580. return;
  34581. }
  34582. this._fillMode = value;
  34583. this.markAsDirty(Material.MiscDirtyFlag);
  34584. },
  34585. enumerable: true,
  34586. configurable: true
  34587. });
  34588. /**
  34589. * Returns a string representation of the current material
  34590. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34591. * @returns a string with material information
  34592. */
  34593. Material.prototype.toString = function (fullDetails) {
  34594. var ret = "Name: " + this.name;
  34595. if (fullDetails) {
  34596. }
  34597. return ret;
  34598. };
  34599. /**
  34600. * Gets the class name of the material
  34601. * @returns a string with the class name of the material
  34602. */
  34603. Material.prototype.getClassName = function () {
  34604. return "Material";
  34605. };
  34606. Object.defineProperty(Material.prototype, "isFrozen", {
  34607. /**
  34608. * Specifies if updates for the material been locked
  34609. */
  34610. get: function () {
  34611. return this.checkReadyOnlyOnce;
  34612. },
  34613. enumerable: true,
  34614. configurable: true
  34615. });
  34616. /**
  34617. * Locks updates for the material
  34618. */
  34619. Material.prototype.freeze = function () {
  34620. this.checkReadyOnlyOnce = true;
  34621. };
  34622. /**
  34623. * Unlocks updates for the material
  34624. */
  34625. Material.prototype.unfreeze = function () {
  34626. this.checkReadyOnlyOnce = false;
  34627. };
  34628. /**
  34629. * Specifies if the material is ready to be used
  34630. * @param mesh defines the mesh to check
  34631. * @param useInstances specifies if instances should be used
  34632. * @returns a boolean indicating if the material is ready to be used
  34633. */
  34634. Material.prototype.isReady = function (mesh, useInstances) {
  34635. return true;
  34636. };
  34637. /**
  34638. * Specifies that the submesh is ready to be used
  34639. * @param mesh defines the mesh to check
  34640. * @param subMesh defines which submesh to check
  34641. * @param useInstances specifies that instances should be used
  34642. * @returns a boolean indicating that the submesh is ready or not
  34643. */
  34644. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34645. return false;
  34646. };
  34647. /**
  34648. * Returns the material effect
  34649. * @returns the effect associated with the material
  34650. */
  34651. Material.prototype.getEffect = function () {
  34652. return this._effect;
  34653. };
  34654. /**
  34655. * Returns the current scene
  34656. * @returns a Scene
  34657. */
  34658. Material.prototype.getScene = function () {
  34659. return this._scene;
  34660. };
  34661. /**
  34662. * Specifies if the material will require alpha blending
  34663. * @returns a boolean specifying if alpha blending is needed
  34664. */
  34665. Material.prototype.needAlphaBlending = function () {
  34666. return (this.alpha < 1.0);
  34667. };
  34668. /**
  34669. * Specifies if the mesh will require alpha blending
  34670. * @param mesh defines the mesh to check
  34671. * @returns a boolean specifying if alpha blending is needed for the mesh
  34672. */
  34673. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34674. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34675. };
  34676. /**
  34677. * Specifies if this material should be rendered in alpha test mode
  34678. * @returns a boolean specifying if an alpha test is needed.
  34679. */
  34680. Material.prototype.needAlphaTesting = function () {
  34681. return false;
  34682. };
  34683. /**
  34684. * Gets the texture used for the alpha test
  34685. * @returns the texture to use for alpha testing
  34686. */
  34687. Material.prototype.getAlphaTestTexture = function () {
  34688. return null;
  34689. };
  34690. /**
  34691. * Marks the material to indicate that it needs to be re-calculated
  34692. */
  34693. Material.prototype.markDirty = function () {
  34694. this._wasPreviouslyReady = false;
  34695. };
  34696. /** @ignore */
  34697. Material.prototype._preBind = function (effect, overrideOrientation) {
  34698. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34699. var engine = this._scene.getEngine();
  34700. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34701. var reverse = orientation === Material.ClockWiseSideOrientation;
  34702. engine.enableEffect(effect ? effect : this._effect);
  34703. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34704. return reverse;
  34705. };
  34706. /**
  34707. * Binds the material to the mesh
  34708. * @param world defines the world transformation matrix
  34709. * @param mesh defines the mesh to bind the material to
  34710. */
  34711. Material.prototype.bind = function (world, mesh) {
  34712. };
  34713. /**
  34714. * Binds the submesh to the material
  34715. * @param world defines the world transformation matrix
  34716. * @param mesh defines the mesh containing the submesh
  34717. * @param subMesh defines the submesh to bind the material to
  34718. */
  34719. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34720. };
  34721. /**
  34722. * Binds the world matrix to the material
  34723. * @param world defines the world transformation matrix
  34724. */
  34725. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34726. };
  34727. /**
  34728. * Binds the scene's uniform buffer to the effect.
  34729. * @param effect defines the effect to bind to the scene uniform buffer
  34730. * @param sceneUbo defines the uniform buffer storing scene data
  34731. */
  34732. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34733. sceneUbo.bindToEffect(effect, "Scene");
  34734. };
  34735. /**
  34736. * Binds the view matrix to the effect
  34737. * @param effect defines the effect to bind the view matrix to
  34738. */
  34739. Material.prototype.bindView = function (effect) {
  34740. if (!this._useUBO) {
  34741. effect.setMatrix("view", this.getScene().getViewMatrix());
  34742. }
  34743. else {
  34744. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34745. }
  34746. };
  34747. /**
  34748. * Binds the view projection matrix to the effect
  34749. * @param effect defines the effect to bind the view projection matrix to
  34750. */
  34751. Material.prototype.bindViewProjection = function (effect) {
  34752. if (!this._useUBO) {
  34753. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34754. }
  34755. else {
  34756. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34757. }
  34758. };
  34759. /**
  34760. * Specifies if material alpha testing should be turned on for the mesh
  34761. * @param mesh defines the mesh to check
  34762. */
  34763. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34764. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34765. };
  34766. /**
  34767. * Processes to execute after binding the material to a mesh
  34768. * @param mesh defines the rendered mesh
  34769. */
  34770. Material.prototype._afterBind = function (mesh) {
  34771. this._scene._cachedMaterial = this;
  34772. if (mesh) {
  34773. this._scene._cachedVisibility = mesh.visibility;
  34774. }
  34775. else {
  34776. this._scene._cachedVisibility = 1;
  34777. }
  34778. if (mesh) {
  34779. this.onBindObservable.notifyObservers(mesh);
  34780. }
  34781. if (this.disableDepthWrite) {
  34782. var engine = this._scene.getEngine();
  34783. this._cachedDepthWriteState = engine.getDepthWrite();
  34784. engine.setDepthWrite(false);
  34785. }
  34786. };
  34787. /**
  34788. * Unbinds the material from the mesh
  34789. */
  34790. Material.prototype.unbind = function () {
  34791. this.onUnBindObservable.notifyObservers(this);
  34792. if (this.disableDepthWrite) {
  34793. var engine = this._scene.getEngine();
  34794. engine.setDepthWrite(this._cachedDepthWriteState);
  34795. }
  34796. };
  34797. /**
  34798. * Gets the active textures from the material
  34799. * @returns an array of textures
  34800. */
  34801. Material.prototype.getActiveTextures = function () {
  34802. return [];
  34803. };
  34804. /**
  34805. * Specifies if the material uses a texture
  34806. * @param texture defines the texture to check against the material
  34807. * @returns a boolean specifying if the material uses the texture
  34808. */
  34809. Material.prototype.hasTexture = function (texture) {
  34810. return false;
  34811. };
  34812. /**
  34813. * Makes a duplicate of the material, and gives it a new name
  34814. * @param name defines the new name for the duplicated material
  34815. * @returns the cloned material
  34816. */
  34817. Material.prototype.clone = function (name) {
  34818. return null;
  34819. };
  34820. /**
  34821. * Gets the meshes bound to the material
  34822. * @returns an array of meshes bound to the material
  34823. */
  34824. Material.prototype.getBindedMeshes = function () {
  34825. var result = new Array();
  34826. for (var index = 0; index < this._scene.meshes.length; index++) {
  34827. var mesh = this._scene.meshes[index];
  34828. if (mesh.material === this) {
  34829. result.push(mesh);
  34830. }
  34831. }
  34832. return result;
  34833. };
  34834. /**
  34835. * Force shader compilation
  34836. * @param mesh defines the mesh associated with this material
  34837. * @param onCompiled defines a function to execute once the material is compiled
  34838. * @param options defines the options to configure the compilation
  34839. */
  34840. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34841. var _this = this;
  34842. var localOptions = __assign({ clipPlane: false }, options);
  34843. var subMesh = new BABYLON.BaseSubMesh();
  34844. var scene = this.getScene();
  34845. var checkReady = function () {
  34846. if (!_this._scene || !_this._scene.getEngine()) {
  34847. return;
  34848. }
  34849. if (subMesh._materialDefines) {
  34850. subMesh._materialDefines._renderId = -1;
  34851. }
  34852. var clipPlaneState = scene.clipPlane;
  34853. if (localOptions.clipPlane) {
  34854. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34855. }
  34856. if (_this.storeEffectOnSubMeshes) {
  34857. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34858. if (onCompiled) {
  34859. onCompiled(_this);
  34860. }
  34861. }
  34862. else {
  34863. setTimeout(checkReady, 16);
  34864. }
  34865. }
  34866. else {
  34867. if (_this.isReady(mesh)) {
  34868. if (onCompiled) {
  34869. onCompiled(_this);
  34870. }
  34871. }
  34872. else {
  34873. setTimeout(checkReady, 16);
  34874. }
  34875. }
  34876. if (localOptions.clipPlane) {
  34877. scene.clipPlane = clipPlaneState;
  34878. }
  34879. };
  34880. checkReady();
  34881. };
  34882. /**
  34883. * Force shader compilation
  34884. * @param mesh defines the mesh that will use this material
  34885. * @param options defines additional options for compiling the shaders
  34886. * @returns a promise that resolves when the compilation completes
  34887. */
  34888. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34889. var _this = this;
  34890. return new Promise(function (resolve) {
  34891. _this.forceCompilation(mesh, function () {
  34892. resolve();
  34893. }, options);
  34894. });
  34895. };
  34896. /**
  34897. * Marks a define in the material to indicate that it needs to be re-computed
  34898. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34899. */
  34900. Material.prototype.markAsDirty = function (flag) {
  34901. if (flag & Material.TextureDirtyFlag) {
  34902. this._markAllSubMeshesAsTexturesDirty();
  34903. }
  34904. if (flag & Material.LightDirtyFlag) {
  34905. this._markAllSubMeshesAsLightsDirty();
  34906. }
  34907. if (flag & Material.FresnelDirtyFlag) {
  34908. this._markAllSubMeshesAsFresnelDirty();
  34909. }
  34910. if (flag & Material.AttributesDirtyFlag) {
  34911. this._markAllSubMeshesAsAttributesDirty();
  34912. }
  34913. if (flag & Material.MiscDirtyFlag) {
  34914. this._markAllSubMeshesAsMiscDirty();
  34915. }
  34916. this.getScene().resetCachedMaterial();
  34917. };
  34918. /**
  34919. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34920. * @param func defines a function which checks material defines against the submeshes
  34921. */
  34922. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34923. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34924. var mesh = _a[_i];
  34925. if (!mesh.subMeshes) {
  34926. continue;
  34927. }
  34928. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34929. var subMesh = _c[_b];
  34930. if (subMesh.getMaterial() !== this) {
  34931. continue;
  34932. }
  34933. if (!subMesh._materialDefines) {
  34934. continue;
  34935. }
  34936. func(subMesh._materialDefines);
  34937. }
  34938. }
  34939. };
  34940. /**
  34941. * Indicates that image processing needs to be re-calculated for all submeshes
  34942. */
  34943. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34944. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34945. };
  34946. /**
  34947. * Indicates that textures need to be re-calculated for all submeshes
  34948. */
  34949. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  34950. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  34951. };
  34952. /**
  34953. * Indicates that fresnel needs to be re-calculated for all submeshes
  34954. */
  34955. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  34956. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  34957. };
  34958. /**
  34959. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  34960. */
  34961. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  34962. this._markAllSubMeshesAsDirty(function (defines) {
  34963. defines.markAsFresnelDirty();
  34964. defines.markAsMiscDirty();
  34965. });
  34966. };
  34967. /**
  34968. * Indicates that lights need to be re-calculated for all submeshes
  34969. */
  34970. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  34971. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  34972. };
  34973. /**
  34974. * Indicates that attributes need to be re-calculated for all submeshes
  34975. */
  34976. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  34977. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  34978. };
  34979. /**
  34980. * Indicates that misc needs to be re-calculated for all submeshes
  34981. */
  34982. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  34983. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  34984. };
  34985. /**
  34986. * Indicates that textures and misc need to be re-calculated for all submeshes
  34987. */
  34988. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  34989. this._markAllSubMeshesAsDirty(function (defines) {
  34990. defines.markAsTexturesDirty();
  34991. defines.markAsMiscDirty();
  34992. });
  34993. };
  34994. /**
  34995. * Disposes the material
  34996. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  34997. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  34998. */
  34999. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35000. // Animations
  35001. this.getScene().stopAnimation(this);
  35002. this.getScene().freeProcessedMaterials();
  35003. // Remove from scene
  35004. var index = this._scene.materials.indexOf(this);
  35005. if (index >= 0) {
  35006. this._scene.materials.splice(index, 1);
  35007. }
  35008. // Remove from meshes
  35009. for (index = 0; index < this._scene.meshes.length; index++) {
  35010. var mesh = this._scene.meshes[index];
  35011. if (mesh.material === this) {
  35012. mesh.material = null;
  35013. if (mesh.geometry) {
  35014. var geometry = (mesh.geometry);
  35015. if (this.storeEffectOnSubMeshes) {
  35016. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35017. var subMesh = _a[_i];
  35018. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35019. if (forceDisposeEffect && subMesh._materialEffect) {
  35020. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35021. }
  35022. }
  35023. }
  35024. else {
  35025. geometry._releaseVertexArrayObject(this._effect);
  35026. }
  35027. }
  35028. }
  35029. }
  35030. this._uniformBuffer.dispose();
  35031. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35032. if (forceDisposeEffect && this._effect) {
  35033. if (!this.storeEffectOnSubMeshes) {
  35034. this._scene.getEngine()._releaseEffect(this._effect);
  35035. }
  35036. this._effect = null;
  35037. }
  35038. // Callback
  35039. this.onDisposeObservable.notifyObservers(this);
  35040. this.onDisposeObservable.clear();
  35041. this.onBindObservable.clear();
  35042. this.onUnBindObservable.clear();
  35043. };
  35044. /**
  35045. * Serializes this material
  35046. * @returns the serialized material object
  35047. */
  35048. Material.prototype.serialize = function () {
  35049. return BABYLON.SerializationHelper.Serialize(this);
  35050. };
  35051. /**
  35052. * Creates a MultiMaterial from parsed MultiMaterial data.
  35053. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35054. * @param scene defines the hosting scene
  35055. * @returns a new MultiMaterial
  35056. */
  35057. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35058. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35059. multiMaterial.id = parsedMultiMaterial.id;
  35060. if (BABYLON.Tags) {
  35061. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35062. }
  35063. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35064. var subMatId = parsedMultiMaterial.materials[matIndex];
  35065. if (subMatId) {
  35066. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35067. }
  35068. else {
  35069. multiMaterial.subMaterials.push(null);
  35070. }
  35071. }
  35072. return multiMaterial;
  35073. };
  35074. /**
  35075. * Creates a material from parsed material data
  35076. * @param parsedMaterial defines parsed material data
  35077. * @param scene defines the hosting scene
  35078. * @param rootUrl defines the root URL to use to load textures
  35079. * @returns a new material
  35080. */
  35081. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35082. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35083. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35084. }
  35085. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35086. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35087. if (!BABYLON.LegacyPBRMaterial) {
  35088. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35089. return;
  35090. }
  35091. }
  35092. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35093. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35094. ;
  35095. };
  35096. // Triangle views
  35097. Material._TriangleFillMode = 0;
  35098. Material._WireFrameFillMode = 1;
  35099. Material._PointFillMode = 2;
  35100. // Draw modes
  35101. Material._PointListDrawMode = 3;
  35102. Material._LineListDrawMode = 4;
  35103. Material._LineLoopDrawMode = 5;
  35104. Material._LineStripDrawMode = 6;
  35105. Material._TriangleStripDrawMode = 7;
  35106. Material._TriangleFanDrawMode = 8;
  35107. /**
  35108. * Stores the clock-wise side orientation
  35109. */
  35110. Material._ClockWiseSideOrientation = 0;
  35111. /**
  35112. * Stores the counter clock-wise side orientation
  35113. */
  35114. Material._CounterClockWiseSideOrientation = 1;
  35115. /**
  35116. * The dirty texture flag value
  35117. */
  35118. Material._TextureDirtyFlag = 1;
  35119. /**
  35120. * The dirty light flag value
  35121. */
  35122. Material._LightDirtyFlag = 2;
  35123. /**
  35124. * The dirty fresnel flag value
  35125. */
  35126. Material._FresnelDirtyFlag = 4;
  35127. /**
  35128. * The dirty attribute flag value
  35129. */
  35130. Material._AttributesDirtyFlag = 8;
  35131. /**
  35132. * The dirty misc flag value
  35133. */
  35134. Material._MiscDirtyFlag = 16;
  35135. __decorate([
  35136. BABYLON.serialize()
  35137. ], Material.prototype, "id", void 0);
  35138. __decorate([
  35139. BABYLON.serialize()
  35140. ], Material.prototype, "name", void 0);
  35141. __decorate([
  35142. BABYLON.serialize()
  35143. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35144. __decorate([
  35145. BABYLON.serialize()
  35146. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35147. __decorate([
  35148. BABYLON.serialize()
  35149. ], Material.prototype, "state", void 0);
  35150. __decorate([
  35151. BABYLON.serialize("alpha")
  35152. ], Material.prototype, "_alpha", void 0);
  35153. __decorate([
  35154. BABYLON.serialize("backFaceCulling")
  35155. ], Material.prototype, "_backFaceCulling", void 0);
  35156. __decorate([
  35157. BABYLON.serialize()
  35158. ], Material.prototype, "sideOrientation", void 0);
  35159. __decorate([
  35160. BABYLON.serialize("alphaMode")
  35161. ], Material.prototype, "_alphaMode", void 0);
  35162. __decorate([
  35163. BABYLON.serialize()
  35164. ], Material.prototype, "_needDepthPrePass", void 0);
  35165. __decorate([
  35166. BABYLON.serialize()
  35167. ], Material.prototype, "disableDepthWrite", void 0);
  35168. __decorate([
  35169. BABYLON.serialize()
  35170. ], Material.prototype, "forceDepthWrite", void 0);
  35171. __decorate([
  35172. BABYLON.serialize()
  35173. ], Material.prototype, "separateCullingPass", void 0);
  35174. __decorate([
  35175. BABYLON.serialize("fogEnabled")
  35176. ], Material.prototype, "_fogEnabled", void 0);
  35177. __decorate([
  35178. BABYLON.serialize()
  35179. ], Material.prototype, "pointSize", void 0);
  35180. __decorate([
  35181. BABYLON.serialize()
  35182. ], Material.prototype, "zOffset", void 0);
  35183. __decorate([
  35184. BABYLON.serialize()
  35185. ], Material.prototype, "wireframe", null);
  35186. __decorate([
  35187. BABYLON.serialize()
  35188. ], Material.prototype, "pointsCloud", null);
  35189. __decorate([
  35190. BABYLON.serialize()
  35191. ], Material.prototype, "fillMode", null);
  35192. return Material;
  35193. }());
  35194. BABYLON.Material = Material;
  35195. })(BABYLON || (BABYLON = {}));
  35196. //# sourceMappingURL=babylon.material.js.map
  35197. var BABYLON;
  35198. (function (BABYLON) {
  35199. var UniformBuffer = /** @class */ (function () {
  35200. /**
  35201. * Uniform buffer objects.
  35202. *
  35203. * Handles blocks of uniform on the GPU.
  35204. *
  35205. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35206. *
  35207. * For more information, please refer to :
  35208. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35209. */
  35210. function UniformBuffer(engine, data, dynamic) {
  35211. this._engine = engine;
  35212. this._noUBO = !engine.supportsUniformBuffers;
  35213. this._dynamic = dynamic;
  35214. this._data = data || [];
  35215. this._uniformLocations = {};
  35216. this._uniformSizes = {};
  35217. this._uniformLocationPointer = 0;
  35218. this._needSync = false;
  35219. if (this._noUBO) {
  35220. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35221. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35222. this.updateFloat = this._updateFloatForEffect;
  35223. this.updateFloat2 = this._updateFloat2ForEffect;
  35224. this.updateFloat3 = this._updateFloat3ForEffect;
  35225. this.updateFloat4 = this._updateFloat4ForEffect;
  35226. this.updateMatrix = this._updateMatrixForEffect;
  35227. this.updateVector3 = this._updateVector3ForEffect;
  35228. this.updateVector4 = this._updateVector4ForEffect;
  35229. this.updateColor3 = this._updateColor3ForEffect;
  35230. this.updateColor4 = this._updateColor4ForEffect;
  35231. }
  35232. else {
  35233. this._engine._uniformBuffers.push(this);
  35234. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35235. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35236. this.updateFloat = this._updateFloatForUniform;
  35237. this.updateFloat2 = this._updateFloat2ForUniform;
  35238. this.updateFloat3 = this._updateFloat3ForUniform;
  35239. this.updateFloat4 = this._updateFloat4ForUniform;
  35240. this.updateMatrix = this._updateMatrixForUniform;
  35241. this.updateVector3 = this._updateVector3ForUniform;
  35242. this.updateVector4 = this._updateVector4ForUniform;
  35243. this.updateColor3 = this._updateColor3ForUniform;
  35244. this.updateColor4 = this._updateColor4ForUniform;
  35245. }
  35246. }
  35247. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35248. // Properties
  35249. /**
  35250. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35251. * or just falling back on setUniformXXX calls.
  35252. */
  35253. get: function () {
  35254. return !this._noUBO;
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35260. /**
  35261. * Indicates if the WebGL underlying uniform buffer is in sync
  35262. * with the javascript cache data.
  35263. */
  35264. get: function () {
  35265. return !this._needSync;
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. /**
  35271. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35272. * Also, a dynamic UniformBuffer will disable cache verification and always
  35273. * update the underlying WebGL uniform buffer to the GPU.
  35274. */
  35275. UniformBuffer.prototype.isDynamic = function () {
  35276. return this._dynamic !== undefined;
  35277. };
  35278. /**
  35279. * The data cache on JS side.
  35280. */
  35281. UniformBuffer.prototype.getData = function () {
  35282. return this._bufferData;
  35283. };
  35284. /**
  35285. * The underlying WebGL Uniform buffer.
  35286. */
  35287. UniformBuffer.prototype.getBuffer = function () {
  35288. return this._buffer;
  35289. };
  35290. /**
  35291. * std140 layout specifies how to align data within an UBO structure.
  35292. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35293. * for specs.
  35294. */
  35295. UniformBuffer.prototype._fillAlignment = function (size) {
  35296. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35297. // and 4x4 matrices
  35298. // TODO : change if other types are used
  35299. var alignment;
  35300. if (size <= 2) {
  35301. alignment = size;
  35302. }
  35303. else {
  35304. alignment = 4;
  35305. }
  35306. if ((this._uniformLocationPointer % alignment) !== 0) {
  35307. var oldPointer = this._uniformLocationPointer;
  35308. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35309. var diff = this._uniformLocationPointer - oldPointer;
  35310. for (var i = 0; i < diff; i++) {
  35311. this._data.push(0);
  35312. }
  35313. }
  35314. };
  35315. /**
  35316. * Adds an uniform in the buffer.
  35317. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35318. * for the layout to be correct !
  35319. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35320. * @param {number|number[]} size Data size, or data directly.
  35321. */
  35322. UniformBuffer.prototype.addUniform = function (name, size) {
  35323. if (this._noUBO) {
  35324. return;
  35325. }
  35326. if (this._uniformLocations[name] !== undefined) {
  35327. // Already existing uniform
  35328. return;
  35329. }
  35330. // This function must be called in the order of the shader layout !
  35331. // size can be the size of the uniform, or data directly
  35332. var data;
  35333. if (size instanceof Array) {
  35334. data = size;
  35335. size = data.length;
  35336. }
  35337. else {
  35338. size = size;
  35339. data = [];
  35340. // Fill with zeros
  35341. for (var i = 0; i < size; i++) {
  35342. data.push(0);
  35343. }
  35344. }
  35345. this._fillAlignment(size);
  35346. this._uniformSizes[name] = size;
  35347. this._uniformLocations[name] = this._uniformLocationPointer;
  35348. this._uniformLocationPointer += size;
  35349. for (var i = 0; i < size; i++) {
  35350. this._data.push(data[i]);
  35351. }
  35352. this._needSync = true;
  35353. };
  35354. /**
  35355. * Wrapper for addUniform.
  35356. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35357. * @param {Matrix} mat A 4x4 matrix.
  35358. */
  35359. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35360. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35361. };
  35362. /**
  35363. * Wrapper for addUniform.
  35364. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35365. * @param {number} x
  35366. * @param {number} y
  35367. */
  35368. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35369. var temp = [x, y];
  35370. this.addUniform(name, temp);
  35371. };
  35372. /**
  35373. * Wrapper for addUniform.
  35374. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35375. * @param {number} x
  35376. * @param {number} y
  35377. * @param {number} z
  35378. */
  35379. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35380. var temp = [x, y, z];
  35381. this.addUniform(name, temp);
  35382. };
  35383. /**
  35384. * Wrapper for addUniform.
  35385. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35386. * @param {Color3} color
  35387. */
  35388. UniformBuffer.prototype.addColor3 = function (name, color) {
  35389. var temp = new Array();
  35390. color.toArray(temp);
  35391. this.addUniform(name, temp);
  35392. };
  35393. /**
  35394. * Wrapper for addUniform.
  35395. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35396. * @param {Color3} color
  35397. * @param {number} alpha
  35398. */
  35399. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35400. var temp = new Array();
  35401. color.toArray(temp);
  35402. temp.push(alpha);
  35403. this.addUniform(name, temp);
  35404. };
  35405. /**
  35406. * Wrapper for addUniform.
  35407. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35408. * @param {Vector3} vector
  35409. */
  35410. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35411. var temp = new Array();
  35412. vector.toArray(temp);
  35413. this.addUniform(name, temp);
  35414. };
  35415. /**
  35416. * Wrapper for addUniform.
  35417. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35418. */
  35419. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35420. this.addUniform(name, 12);
  35421. };
  35422. /**
  35423. * Wrapper for addUniform.
  35424. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35425. */
  35426. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35427. this.addUniform(name, 8);
  35428. };
  35429. /**
  35430. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35431. */
  35432. UniformBuffer.prototype.create = function () {
  35433. if (this._noUBO) {
  35434. return;
  35435. }
  35436. if (this._buffer) {
  35437. return; // nothing to do
  35438. }
  35439. // See spec, alignment must be filled as a vec4
  35440. this._fillAlignment(4);
  35441. this._bufferData = new Float32Array(this._data);
  35442. this._rebuild();
  35443. this._needSync = true;
  35444. };
  35445. UniformBuffer.prototype._rebuild = function () {
  35446. if (this._noUBO) {
  35447. return;
  35448. }
  35449. if (this._dynamic) {
  35450. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35451. }
  35452. else {
  35453. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35454. }
  35455. };
  35456. /**
  35457. * Updates the WebGL Uniform Buffer on the GPU.
  35458. * If the `dynamic` flag is set to true, no cache comparison is done.
  35459. * Otherwise, the buffer will be updated only if the cache differs.
  35460. */
  35461. UniformBuffer.prototype.update = function () {
  35462. if (!this._buffer) {
  35463. this.create();
  35464. return;
  35465. }
  35466. if (!this._dynamic && !this._needSync) {
  35467. return;
  35468. }
  35469. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35470. this._needSync = false;
  35471. };
  35472. /**
  35473. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35474. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35475. * @param {number[]|Float32Array} data Flattened data
  35476. * @param {number} size Size of the data.
  35477. */
  35478. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35479. var location = this._uniformLocations[uniformName];
  35480. if (location === undefined) {
  35481. if (this._buffer) {
  35482. // Cannot add an uniform if the buffer is already created
  35483. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35484. return;
  35485. }
  35486. this.addUniform(uniformName, size);
  35487. location = this._uniformLocations[uniformName];
  35488. }
  35489. if (!this._buffer) {
  35490. this.create();
  35491. }
  35492. if (!this._dynamic) {
  35493. // Cache for static uniform buffers
  35494. var changed = false;
  35495. for (var i = 0; i < size; i++) {
  35496. if (this._bufferData[location + i] !== data[i]) {
  35497. changed = true;
  35498. this._bufferData[location + i] = data[i];
  35499. }
  35500. }
  35501. this._needSync = this._needSync || changed;
  35502. }
  35503. else {
  35504. // No cache for dynamic
  35505. for (var i = 0; i < size; i++) {
  35506. this._bufferData[location + i] = data[i];
  35507. }
  35508. }
  35509. };
  35510. // Update methods
  35511. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35512. // To match std140, matrix must be realigned
  35513. for (var i = 0; i < 3; i++) {
  35514. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35515. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35516. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35517. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35518. }
  35519. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35520. };
  35521. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35522. this._currentEffect.setMatrix3x3(name, matrix);
  35523. };
  35524. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35525. this._currentEffect.setMatrix2x2(name, matrix);
  35526. };
  35527. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35528. // To match std140, matrix must be realigned
  35529. for (var i = 0; i < 2; i++) {
  35530. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35531. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35532. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35533. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35534. }
  35535. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35536. };
  35537. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35538. this._currentEffect.setFloat(name, x);
  35539. };
  35540. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35541. UniformBuffer._tempBuffer[0] = x;
  35542. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35543. };
  35544. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35545. if (suffix === void 0) { suffix = ""; }
  35546. this._currentEffect.setFloat2(name + suffix, x, y);
  35547. };
  35548. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35549. if (suffix === void 0) { suffix = ""; }
  35550. UniformBuffer._tempBuffer[0] = x;
  35551. UniformBuffer._tempBuffer[1] = y;
  35552. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35553. };
  35554. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35555. if (suffix === void 0) { suffix = ""; }
  35556. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35557. };
  35558. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35559. if (suffix === void 0) { suffix = ""; }
  35560. UniformBuffer._tempBuffer[0] = x;
  35561. UniformBuffer._tempBuffer[1] = y;
  35562. UniformBuffer._tempBuffer[2] = z;
  35563. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35564. };
  35565. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35566. if (suffix === void 0) { suffix = ""; }
  35567. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35568. };
  35569. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35570. if (suffix === void 0) { suffix = ""; }
  35571. UniformBuffer._tempBuffer[0] = x;
  35572. UniformBuffer._tempBuffer[1] = y;
  35573. UniformBuffer._tempBuffer[2] = z;
  35574. UniformBuffer._tempBuffer[3] = w;
  35575. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35576. };
  35577. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35578. this._currentEffect.setMatrix(name, mat);
  35579. };
  35580. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35581. this.updateUniform(name, mat.toArray(), 16);
  35582. };
  35583. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35584. this._currentEffect.setVector3(name, vector);
  35585. };
  35586. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35587. vector.toArray(UniformBuffer._tempBuffer);
  35588. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35589. };
  35590. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35591. this._currentEffect.setVector4(name, vector);
  35592. };
  35593. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35594. vector.toArray(UniformBuffer._tempBuffer);
  35595. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35596. };
  35597. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35598. if (suffix === void 0) { suffix = ""; }
  35599. this._currentEffect.setColor3(name + suffix, color);
  35600. };
  35601. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35602. if (suffix === void 0) { suffix = ""; }
  35603. color.toArray(UniformBuffer._tempBuffer);
  35604. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35605. };
  35606. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35607. if (suffix === void 0) { suffix = ""; }
  35608. this._currentEffect.setColor4(name + suffix, color, alpha);
  35609. };
  35610. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35611. if (suffix === void 0) { suffix = ""; }
  35612. color.toArray(UniformBuffer._tempBuffer);
  35613. UniformBuffer._tempBuffer[3] = alpha;
  35614. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35615. };
  35616. /**
  35617. * Sets a sampler uniform on the effect.
  35618. * @param {string} name Name of the sampler.
  35619. * @param {Texture} texture
  35620. */
  35621. UniformBuffer.prototype.setTexture = function (name, texture) {
  35622. this._currentEffect.setTexture(name, texture);
  35623. };
  35624. /**
  35625. * Directly updates the value of the uniform in the cache AND on the GPU.
  35626. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35627. * @param {number[]|Float32Array} data Flattened data
  35628. */
  35629. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35630. this.updateUniform(uniformName, data, data.length);
  35631. this.update();
  35632. };
  35633. /**
  35634. * Binds this uniform buffer to an effect.
  35635. * @param {Effect} effect
  35636. * @param {string} name Name of the uniform block in the shader.
  35637. */
  35638. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35639. this._currentEffect = effect;
  35640. if (this._noUBO || !this._buffer) {
  35641. return;
  35642. }
  35643. effect.bindUniformBuffer(this._buffer, name);
  35644. };
  35645. /**
  35646. * Disposes the uniform buffer.
  35647. */
  35648. UniformBuffer.prototype.dispose = function () {
  35649. if (this._noUBO) {
  35650. return;
  35651. }
  35652. var index = this._engine._uniformBuffers.indexOf(this);
  35653. if (index !== -1) {
  35654. this._engine._uniformBuffers.splice(index, 1);
  35655. }
  35656. if (!this._buffer) {
  35657. return;
  35658. }
  35659. if (this._engine._releaseBuffer(this._buffer)) {
  35660. this._buffer = null;
  35661. }
  35662. };
  35663. // Pool for avoiding memory leaks
  35664. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35665. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35666. return UniformBuffer;
  35667. }());
  35668. BABYLON.UniformBuffer = UniformBuffer;
  35669. })(BABYLON || (BABYLON = {}));
  35670. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35671. var BABYLON;
  35672. (function (BABYLON) {
  35673. /**
  35674. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35675. */
  35676. var VertexData = /** @class */ (function () {
  35677. function VertexData() {
  35678. }
  35679. /**
  35680. * Uses the passed data array to set the set the values for the specified kind of data
  35681. * @param data a linear array of floating numbers
  35682. * @param kind the type of data that is being set, eg positions, colors etc
  35683. */
  35684. VertexData.prototype.set = function (data, kind) {
  35685. switch (kind) {
  35686. case BABYLON.VertexBuffer.PositionKind:
  35687. this.positions = data;
  35688. break;
  35689. case BABYLON.VertexBuffer.NormalKind:
  35690. this.normals = data;
  35691. break;
  35692. case BABYLON.VertexBuffer.TangentKind:
  35693. this.tangents = data;
  35694. break;
  35695. case BABYLON.VertexBuffer.UVKind:
  35696. this.uvs = data;
  35697. break;
  35698. case BABYLON.VertexBuffer.UV2Kind:
  35699. this.uvs2 = data;
  35700. break;
  35701. case BABYLON.VertexBuffer.UV3Kind:
  35702. this.uvs3 = data;
  35703. break;
  35704. case BABYLON.VertexBuffer.UV4Kind:
  35705. this.uvs4 = data;
  35706. break;
  35707. case BABYLON.VertexBuffer.UV5Kind:
  35708. this.uvs5 = data;
  35709. break;
  35710. case BABYLON.VertexBuffer.UV6Kind:
  35711. this.uvs6 = data;
  35712. break;
  35713. case BABYLON.VertexBuffer.ColorKind:
  35714. this.colors = data;
  35715. break;
  35716. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35717. this.matricesIndices = data;
  35718. break;
  35719. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35720. this.matricesWeights = data;
  35721. break;
  35722. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35723. this.matricesIndicesExtra = data;
  35724. break;
  35725. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35726. this.matricesWeightsExtra = data;
  35727. break;
  35728. }
  35729. };
  35730. /**
  35731. * Associates the vertexData to the passed Mesh.
  35732. * Sets it as updatable or not (default `false`)
  35733. * @param mesh the mesh the vertexData is applied to
  35734. * @param updatable when used and having the value true allows new data to update the vertexData
  35735. * @returns the VertexData
  35736. */
  35737. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35738. this._applyTo(mesh, updatable);
  35739. return this;
  35740. };
  35741. /**
  35742. * Associates the vertexData to the passed Geometry.
  35743. * Sets it as updatable or not (default `false`)
  35744. * @param geometry the geometry the vertexData is applied to
  35745. * @param updatable when used and having the value true allows new data to update the vertexData
  35746. * @returns VertexData
  35747. */
  35748. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35749. this._applyTo(geometry, updatable);
  35750. return this;
  35751. };
  35752. /**
  35753. * Updates the associated mesh
  35754. * @param mesh the mesh to be updated
  35755. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35756. * @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
  35757. * @returns VertexData
  35758. */
  35759. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35760. this._update(mesh);
  35761. return this;
  35762. };
  35763. /**
  35764. * Updates the associated geometry
  35765. * @param geometry the geometry to be updated
  35766. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35767. * @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
  35768. * @returns VertexData.
  35769. */
  35770. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35771. this._update(geometry);
  35772. return this;
  35773. };
  35774. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35775. if (updatable === void 0) { updatable = false; }
  35776. if (this.positions) {
  35777. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35778. }
  35779. if (this.normals) {
  35780. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35781. }
  35782. if (this.tangents) {
  35783. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35784. }
  35785. if (this.uvs) {
  35786. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35787. }
  35788. if (this.uvs2) {
  35789. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35790. }
  35791. if (this.uvs3) {
  35792. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35793. }
  35794. if (this.uvs4) {
  35795. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35796. }
  35797. if (this.uvs5) {
  35798. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35799. }
  35800. if (this.uvs6) {
  35801. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35802. }
  35803. if (this.colors) {
  35804. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35805. }
  35806. if (this.matricesIndices) {
  35807. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35808. }
  35809. if (this.matricesWeights) {
  35810. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35811. }
  35812. if (this.matricesIndicesExtra) {
  35813. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35814. }
  35815. if (this.matricesWeightsExtra) {
  35816. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35817. }
  35818. if (this.indices) {
  35819. meshOrGeometry.setIndices(this.indices, null, updatable);
  35820. }
  35821. return this;
  35822. };
  35823. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35824. if (this.positions) {
  35825. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35826. }
  35827. if (this.normals) {
  35828. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35829. }
  35830. if (this.tangents) {
  35831. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35832. }
  35833. if (this.uvs) {
  35834. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35835. }
  35836. if (this.uvs2) {
  35837. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35838. }
  35839. if (this.uvs3) {
  35840. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35841. }
  35842. if (this.uvs4) {
  35843. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35844. }
  35845. if (this.uvs5) {
  35846. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35847. }
  35848. if (this.uvs6) {
  35849. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35850. }
  35851. if (this.colors) {
  35852. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35853. }
  35854. if (this.matricesIndices) {
  35855. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35856. }
  35857. if (this.matricesWeights) {
  35858. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35859. }
  35860. if (this.matricesIndicesExtra) {
  35861. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35862. }
  35863. if (this.matricesWeightsExtra) {
  35864. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35865. }
  35866. if (this.indices) {
  35867. meshOrGeometry.setIndices(this.indices, null);
  35868. }
  35869. return this;
  35870. };
  35871. /**
  35872. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35873. * @param matrix the transforming matrix
  35874. * @returns the VertexData
  35875. */
  35876. VertexData.prototype.transform = function (matrix) {
  35877. var transformed = BABYLON.Vector3.Zero();
  35878. var index;
  35879. if (this.positions) {
  35880. var position = BABYLON.Vector3.Zero();
  35881. for (index = 0; index < this.positions.length; index += 3) {
  35882. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35883. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35884. this.positions[index] = transformed.x;
  35885. this.positions[index + 1] = transformed.y;
  35886. this.positions[index + 2] = transformed.z;
  35887. }
  35888. }
  35889. if (this.normals) {
  35890. var normal = BABYLON.Vector3.Zero();
  35891. for (index = 0; index < this.normals.length; index += 3) {
  35892. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35893. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35894. this.normals[index] = transformed.x;
  35895. this.normals[index + 1] = transformed.y;
  35896. this.normals[index + 2] = transformed.z;
  35897. }
  35898. }
  35899. if (this.tangents) {
  35900. var tangent = BABYLON.Vector4.Zero();
  35901. var tangentTransformed = BABYLON.Vector4.Zero();
  35902. for (index = 0; index < this.tangents.length; index += 4) {
  35903. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35904. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35905. this.tangents[index] = tangentTransformed.x;
  35906. this.tangents[index + 1] = tangentTransformed.y;
  35907. this.tangents[index + 2] = tangentTransformed.z;
  35908. this.tangents[index + 3] = tangentTransformed.w;
  35909. }
  35910. }
  35911. return this;
  35912. };
  35913. /**
  35914. * Merges the passed VertexData into the current one
  35915. * @param other the VertexData to be merged into the current one
  35916. * @returns the modified VertexData
  35917. */
  35918. VertexData.prototype.merge = function (other) {
  35919. this._validate();
  35920. other._validate();
  35921. if (!this.normals !== !other.normals ||
  35922. !this.tangents !== !other.tangents ||
  35923. !this.uvs !== !other.uvs ||
  35924. !this.uvs2 !== !other.uvs2 ||
  35925. !this.uvs3 !== !other.uvs3 ||
  35926. !this.uvs4 !== !other.uvs4 ||
  35927. !this.uvs5 !== !other.uvs5 ||
  35928. !this.uvs6 !== !other.uvs6 ||
  35929. !this.colors !== !other.colors ||
  35930. !this.matricesIndices !== !other.matricesIndices ||
  35931. !this.matricesWeights !== !other.matricesWeights ||
  35932. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35933. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35934. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35935. }
  35936. if (other.indices) {
  35937. if (!this.indices) {
  35938. this.indices = [];
  35939. }
  35940. var offset = this.positions ? this.positions.length / 3 : 0;
  35941. for (var index = 0; index < other.indices.length; index++) {
  35942. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35943. this.indices.push(other.indices[index] + offset);
  35944. }
  35945. }
  35946. this.positions = this._mergeElement(this.positions, other.positions);
  35947. this.normals = this._mergeElement(this.normals, other.normals);
  35948. this.tangents = this._mergeElement(this.tangents, other.tangents);
  35949. this.uvs = this._mergeElement(this.uvs, other.uvs);
  35950. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  35951. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  35952. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  35953. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  35954. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  35955. this.colors = this._mergeElement(this.colors, other.colors);
  35956. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  35957. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  35958. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  35959. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  35960. return this;
  35961. };
  35962. VertexData.prototype._mergeElement = function (source, other) {
  35963. if (!source) {
  35964. return other;
  35965. }
  35966. if (!other) {
  35967. return source;
  35968. }
  35969. var len = other.length + source.length;
  35970. var isSrcTypedArray = source instanceof Float32Array;
  35971. var isOthTypedArray = other instanceof Float32Array;
  35972. // use non-loop method when the source is Float32Array
  35973. if (isSrcTypedArray) {
  35974. var ret32 = new Float32Array(len);
  35975. ret32.set(source);
  35976. ret32.set(other, source.length);
  35977. return ret32;
  35978. // source is number[], when other is also use concat
  35979. }
  35980. else if (!isOthTypedArray) {
  35981. return source.concat(other);
  35982. // source is a number[], but other is a Float32Array, loop required
  35983. }
  35984. else {
  35985. var ret = source.slice(0); // copy source to a separate array
  35986. for (var i = 0, len = other.length; i < len; i++) {
  35987. ret.push(other[i]);
  35988. }
  35989. return ret;
  35990. }
  35991. };
  35992. VertexData.prototype._validate = function () {
  35993. if (!this.positions) {
  35994. throw new Error("Positions are required");
  35995. }
  35996. var getElementCount = function (kind, values) {
  35997. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  35998. if ((values.length % stride) !== 0) {
  35999. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36000. }
  36001. return values.length / stride;
  36002. };
  36003. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36004. var validateElementCount = function (kind, values) {
  36005. var elementCount = getElementCount(kind, values);
  36006. if (elementCount !== positionsElementCount) {
  36007. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36008. }
  36009. };
  36010. if (this.normals)
  36011. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36012. if (this.tangents)
  36013. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36014. if (this.uvs)
  36015. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36016. if (this.uvs2)
  36017. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36018. if (this.uvs3)
  36019. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36020. if (this.uvs4)
  36021. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36022. if (this.uvs5)
  36023. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36024. if (this.uvs6)
  36025. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36026. if (this.colors)
  36027. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36028. if (this.matricesIndices)
  36029. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36030. if (this.matricesWeights)
  36031. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36032. if (this.matricesIndicesExtra)
  36033. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36034. if (this.matricesWeightsExtra)
  36035. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36036. };
  36037. /**
  36038. * Serializes the VertexData
  36039. * @returns a serialized object
  36040. */
  36041. VertexData.prototype.serialize = function () {
  36042. var serializationObject = this.serialize();
  36043. if (this.positions) {
  36044. serializationObject.positions = this.positions;
  36045. }
  36046. if (this.normals) {
  36047. serializationObject.normals = this.normals;
  36048. }
  36049. if (this.tangents) {
  36050. serializationObject.tangents = this.tangents;
  36051. }
  36052. if (this.uvs) {
  36053. serializationObject.uvs = this.uvs;
  36054. }
  36055. if (this.uvs2) {
  36056. serializationObject.uvs2 = this.uvs2;
  36057. }
  36058. if (this.uvs3) {
  36059. serializationObject.uvs3 = this.uvs3;
  36060. }
  36061. if (this.uvs4) {
  36062. serializationObject.uvs4 = this.uvs4;
  36063. }
  36064. if (this.uvs5) {
  36065. serializationObject.uvs5 = this.uvs5;
  36066. }
  36067. if (this.uvs6) {
  36068. serializationObject.uvs6 = this.uvs6;
  36069. }
  36070. if (this.colors) {
  36071. serializationObject.colors = this.colors;
  36072. }
  36073. if (this.matricesIndices) {
  36074. serializationObject.matricesIndices = this.matricesIndices;
  36075. serializationObject.matricesIndices._isExpanded = true;
  36076. }
  36077. if (this.matricesWeights) {
  36078. serializationObject.matricesWeights = this.matricesWeights;
  36079. }
  36080. if (this.matricesIndicesExtra) {
  36081. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36082. serializationObject.matricesIndicesExtra._isExpanded = true;
  36083. }
  36084. if (this.matricesWeightsExtra) {
  36085. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36086. }
  36087. serializationObject.indices = this.indices;
  36088. return serializationObject;
  36089. };
  36090. // Statics
  36091. /**
  36092. * Extracts the vertexData from a mesh
  36093. * @param mesh the mesh from which to extract the VertexData
  36094. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36095. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36096. * @returns the object VertexData associated to the passed mesh
  36097. */
  36098. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36099. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36100. };
  36101. /**
  36102. * Extracts the vertexData from the geometry
  36103. * @param geometry the geometry from which to extract the VertexData
  36104. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36105. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36106. * @returns the object VertexData associated to the passed mesh
  36107. */
  36108. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36109. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36110. };
  36111. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36112. var result = new VertexData();
  36113. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36114. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36115. }
  36116. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36117. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36118. }
  36119. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36120. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36121. }
  36122. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36123. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36124. }
  36125. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36126. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36127. }
  36128. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36129. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36130. }
  36131. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36132. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36133. }
  36134. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36135. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36136. }
  36137. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36138. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36139. }
  36140. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36141. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36142. }
  36143. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36144. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36145. }
  36146. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36147. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36148. }
  36149. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36150. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36151. }
  36152. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36153. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36154. }
  36155. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36156. return result;
  36157. };
  36158. /**
  36159. * Creates the VertexData for a Ribbon
  36160. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36161. * * pathArray array of paths, each of which an array of successive Vector3
  36162. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36163. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36164. * * 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
  36165. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36166. * * 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)
  36167. * * 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)
  36168. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36169. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36170. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36171. * @returns the VertexData of the ribbon
  36172. */
  36173. VertexData.CreateRibbon = function (options) {
  36174. var pathArray = options.pathArray;
  36175. var closeArray = options.closeArray || false;
  36176. var closePath = options.closePath || false;
  36177. var invertUV = options.invertUV || false;
  36178. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36179. var offset = options.offset || defaultOffset;
  36180. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36181. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36182. var customUV = options.uvs;
  36183. var customColors = options.colors;
  36184. var positions = [];
  36185. var indices = [];
  36186. var normals = [];
  36187. var uvs = [];
  36188. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36189. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36190. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36191. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36192. var minlg; // minimal length among all paths from pathArray
  36193. var lg = []; // array of path lengths : nb of vertex per path
  36194. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36195. var p; // path iterator
  36196. var i; // point iterator
  36197. var j; // point iterator
  36198. // if single path in pathArray
  36199. if (pathArray.length < 2) {
  36200. var ar1 = [];
  36201. var ar2 = [];
  36202. for (i = 0; i < pathArray[0].length - offset; i++) {
  36203. ar1.push(pathArray[0][i]);
  36204. ar2.push(pathArray[0][i + offset]);
  36205. }
  36206. pathArray = [ar1, ar2];
  36207. }
  36208. // positions and horizontal distances (u)
  36209. var idc = 0;
  36210. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36211. var path;
  36212. var l;
  36213. minlg = pathArray[0].length;
  36214. var vectlg;
  36215. var dist;
  36216. for (p = 0; p < pathArray.length; p++) {
  36217. uTotalDistance[p] = 0;
  36218. us[p] = [0];
  36219. path = pathArray[p];
  36220. l = path.length;
  36221. minlg = (minlg < l) ? minlg : l;
  36222. j = 0;
  36223. while (j < l) {
  36224. positions.push(path[j].x, path[j].y, path[j].z);
  36225. if (j > 0) {
  36226. vectlg = path[j].subtract(path[j - 1]).length();
  36227. dist = vectlg + uTotalDistance[p];
  36228. us[p].push(dist);
  36229. uTotalDistance[p] = dist;
  36230. }
  36231. j++;
  36232. }
  36233. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36234. j--;
  36235. positions.push(path[0].x, path[0].y, path[0].z);
  36236. vectlg = path[j].subtract(path[0]).length();
  36237. dist = vectlg + uTotalDistance[p];
  36238. us[p].push(dist);
  36239. uTotalDistance[p] = dist;
  36240. }
  36241. lg[p] = l + closePathCorr;
  36242. idx[p] = idc;
  36243. idc += (l + closePathCorr);
  36244. }
  36245. // vertical distances (v)
  36246. var path1;
  36247. var path2;
  36248. var vertex1 = null;
  36249. var vertex2 = null;
  36250. for (i = 0; i < minlg + closePathCorr; i++) {
  36251. vTotalDistance[i] = 0;
  36252. vs[i] = [0];
  36253. for (p = 0; p < pathArray.length - 1; p++) {
  36254. path1 = pathArray[p];
  36255. path2 = pathArray[p + 1];
  36256. if (i === minlg) { // closePath
  36257. vertex1 = path1[0];
  36258. vertex2 = path2[0];
  36259. }
  36260. else {
  36261. vertex1 = path1[i];
  36262. vertex2 = path2[i];
  36263. }
  36264. vectlg = vertex2.subtract(vertex1).length();
  36265. dist = vectlg + vTotalDistance[i];
  36266. vs[i].push(dist);
  36267. vTotalDistance[i] = dist;
  36268. }
  36269. if (closeArray && vertex2 && vertex1) {
  36270. path1 = pathArray[p];
  36271. path2 = pathArray[0];
  36272. if (i === minlg) { // closePath
  36273. vertex2 = path2[0];
  36274. }
  36275. vectlg = vertex2.subtract(vertex1).length();
  36276. dist = vectlg + vTotalDistance[i];
  36277. vTotalDistance[i] = dist;
  36278. }
  36279. }
  36280. // uvs
  36281. var u;
  36282. var v;
  36283. if (customUV) {
  36284. for (p = 0; p < customUV.length; p++) {
  36285. uvs.push(customUV[p].x, customUV[p].y);
  36286. }
  36287. }
  36288. else {
  36289. for (p = 0; p < pathArray.length; p++) {
  36290. for (i = 0; i < minlg + closePathCorr; i++) {
  36291. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36292. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36293. if (invertUV) {
  36294. uvs.push(v, u);
  36295. }
  36296. else {
  36297. uvs.push(u, v);
  36298. }
  36299. }
  36300. }
  36301. }
  36302. // indices
  36303. p = 0; // path index
  36304. var pi = 0; // positions array index
  36305. var l1 = lg[p] - 1; // path1 length
  36306. var l2 = lg[p + 1] - 1; // path2 length
  36307. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36308. var shft = idx[1] - idx[0]; // shift
  36309. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36310. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36311. // 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
  36312. indices.push(pi, pi + shft, pi + 1);
  36313. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36314. pi += 1;
  36315. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36316. p++;
  36317. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36318. shft = idx[0] - idx[p];
  36319. l1 = lg[p] - 1;
  36320. l2 = lg[0] - 1;
  36321. }
  36322. else {
  36323. shft = idx[p + 1] - idx[p];
  36324. l1 = lg[p] - 1;
  36325. l2 = lg[p + 1] - 1;
  36326. }
  36327. pi = idx[p];
  36328. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36329. }
  36330. }
  36331. // normals
  36332. VertexData.ComputeNormals(positions, indices, normals);
  36333. if (closePath) { // update both the first and last vertex normals to their average value
  36334. var indexFirst = 0;
  36335. var indexLast = 0;
  36336. for (p = 0; p < pathArray.length; p++) {
  36337. indexFirst = idx[p] * 3;
  36338. if (p + 1 < pathArray.length) {
  36339. indexLast = (idx[p + 1] - 1) * 3;
  36340. }
  36341. else {
  36342. indexLast = normals.length - 3;
  36343. }
  36344. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36345. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36346. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36347. normals[indexLast] = normals[indexFirst];
  36348. normals[indexLast + 1] = normals[indexFirst + 1];
  36349. normals[indexLast + 2] = normals[indexFirst + 2];
  36350. }
  36351. }
  36352. // sides
  36353. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36354. // Colors
  36355. var colors = null;
  36356. if (customColors) {
  36357. colors = new Float32Array(customColors.length * 4);
  36358. for (var c = 0; c < customColors.length; c++) {
  36359. colors[c * 4] = customColors[c].r;
  36360. colors[c * 4 + 1] = customColors[c].g;
  36361. colors[c * 4 + 2] = customColors[c].b;
  36362. colors[c * 4 + 3] = customColors[c].a;
  36363. }
  36364. }
  36365. // Result
  36366. var vertexData = new VertexData();
  36367. var positions32 = new Float32Array(positions);
  36368. var normals32 = new Float32Array(normals);
  36369. var uvs32 = new Float32Array(uvs);
  36370. vertexData.indices = indices;
  36371. vertexData.positions = positions32;
  36372. vertexData.normals = normals32;
  36373. vertexData.uvs = uvs32;
  36374. if (colors) {
  36375. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36376. }
  36377. if (closePath) {
  36378. vertexData._idx = idx;
  36379. }
  36380. return vertexData;
  36381. };
  36382. /**
  36383. * Creates the VertexData for a box
  36384. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36385. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36386. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36387. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36388. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36389. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36390. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36391. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36392. * * 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)
  36393. * * 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)
  36394. * @returns the VertexData of the box
  36395. */
  36396. VertexData.CreateBox = function (options) {
  36397. var normalsSource = [
  36398. new BABYLON.Vector3(0, 0, 1),
  36399. new BABYLON.Vector3(0, 0, -1),
  36400. new BABYLON.Vector3(1, 0, 0),
  36401. new BABYLON.Vector3(-1, 0, 0),
  36402. new BABYLON.Vector3(0, 1, 0),
  36403. new BABYLON.Vector3(0, -1, 0)
  36404. ];
  36405. var indices = [];
  36406. var positions = [];
  36407. var normals = [];
  36408. var uvs = [];
  36409. var width = options.width || options.size || 1;
  36410. var height = options.height || options.size || 1;
  36411. var depth = options.depth || options.size || 1;
  36412. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36413. var faceUV = options.faceUV || new Array(6);
  36414. var faceColors = options.faceColors;
  36415. var colors = [];
  36416. // default face colors and UV if undefined
  36417. for (var f = 0; f < 6; f++) {
  36418. if (faceUV[f] === undefined) {
  36419. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36420. }
  36421. if (faceColors && faceColors[f] === undefined) {
  36422. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36423. }
  36424. }
  36425. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36426. // Create each face in turn.
  36427. for (var index = 0; index < normalsSource.length; index++) {
  36428. var normal = normalsSource[index];
  36429. // Get two vectors perpendicular to the face normal and to each other.
  36430. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36431. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36432. // Six indices (two triangles) per face.
  36433. var verticesLength = positions.length / 3;
  36434. indices.push(verticesLength);
  36435. indices.push(verticesLength + 1);
  36436. indices.push(verticesLength + 2);
  36437. indices.push(verticesLength);
  36438. indices.push(verticesLength + 2);
  36439. indices.push(verticesLength + 3);
  36440. // Four vertices per face.
  36441. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36442. positions.push(vertex.x, vertex.y, vertex.z);
  36443. normals.push(normal.x, normal.y, normal.z);
  36444. uvs.push(faceUV[index].z, faceUV[index].w);
  36445. if (faceColors) {
  36446. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36447. }
  36448. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36449. positions.push(vertex.x, vertex.y, vertex.z);
  36450. normals.push(normal.x, normal.y, normal.z);
  36451. uvs.push(faceUV[index].x, faceUV[index].w);
  36452. if (faceColors) {
  36453. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36454. }
  36455. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36456. positions.push(vertex.x, vertex.y, vertex.z);
  36457. normals.push(normal.x, normal.y, normal.z);
  36458. uvs.push(faceUV[index].x, faceUV[index].y);
  36459. if (faceColors) {
  36460. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36461. }
  36462. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36463. positions.push(vertex.x, vertex.y, vertex.z);
  36464. normals.push(normal.x, normal.y, normal.z);
  36465. uvs.push(faceUV[index].z, faceUV[index].y);
  36466. if (faceColors) {
  36467. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36468. }
  36469. }
  36470. // sides
  36471. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36472. // Result
  36473. var vertexData = new VertexData();
  36474. vertexData.indices = indices;
  36475. vertexData.positions = positions;
  36476. vertexData.normals = normals;
  36477. vertexData.uvs = uvs;
  36478. if (faceColors) {
  36479. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36480. vertexData.colors = totalColors;
  36481. }
  36482. return vertexData;
  36483. };
  36484. /**
  36485. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36486. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36487. * * segments sets the number of horizontal strips optional, default 32
  36488. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36489. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36490. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36491. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36492. * * 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
  36493. * * 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
  36494. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36495. * * 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)
  36496. * * 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)
  36497. * @returns the VertexData of the ellipsoid
  36498. */
  36499. VertexData.CreateSphere = function (options) {
  36500. var segments = options.segments || 32;
  36501. var diameterX = options.diameterX || options.diameter || 1;
  36502. var diameterY = options.diameterY || options.diameter || 1;
  36503. var diameterZ = options.diameterZ || options.diameter || 1;
  36504. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36505. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36506. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36507. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36508. var totalZRotationSteps = 2 + segments;
  36509. var totalYRotationSteps = 2 * totalZRotationSteps;
  36510. var indices = [];
  36511. var positions = [];
  36512. var normals = [];
  36513. var uvs = [];
  36514. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36515. var normalizedZ = zRotationStep / totalZRotationSteps;
  36516. var angleZ = normalizedZ * Math.PI * slice;
  36517. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36518. var normalizedY = yRotationStep / totalYRotationSteps;
  36519. var angleY = normalizedY * Math.PI * 2 * arc;
  36520. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36521. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36522. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36523. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36524. var vertex = complete.multiply(radius);
  36525. var normal = complete.divide(radius).normalize();
  36526. positions.push(vertex.x, vertex.y, vertex.z);
  36527. normals.push(normal.x, normal.y, normal.z);
  36528. uvs.push(normalizedY, normalizedZ);
  36529. }
  36530. if (zRotationStep > 0) {
  36531. var verticesCount = positions.length / 3;
  36532. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36533. indices.push((firstIndex));
  36534. indices.push((firstIndex + 1));
  36535. indices.push(firstIndex + totalYRotationSteps + 1);
  36536. indices.push((firstIndex + totalYRotationSteps + 1));
  36537. indices.push((firstIndex + 1));
  36538. indices.push((firstIndex + totalYRotationSteps + 2));
  36539. }
  36540. }
  36541. }
  36542. // Sides
  36543. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36544. // Result
  36545. var vertexData = new VertexData();
  36546. vertexData.indices = indices;
  36547. vertexData.positions = positions;
  36548. vertexData.normals = normals;
  36549. vertexData.uvs = uvs;
  36550. return vertexData;
  36551. };
  36552. /**
  36553. * Creates the VertexData for a cylinder, cone or prism
  36554. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36555. * * height sets the height (y direction) of the cylinder, optional, default 2
  36556. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36557. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36558. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36559. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36560. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36561. * * 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
  36562. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36563. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36564. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36565. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36566. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36567. * * 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)
  36568. * * 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)
  36569. * @returns the VertexData of the cylinder, cone or prism
  36570. */
  36571. VertexData.CreateCylinder = function (options) {
  36572. var height = options.height || 2;
  36573. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36574. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36575. var tessellation = options.tessellation || 24;
  36576. var subdivisions = options.subdivisions || 1;
  36577. var hasRings = options.hasRings ? true : false;
  36578. var enclose = options.enclose ? true : false;
  36579. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36580. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36581. var faceUV = options.faceUV || new Array(3);
  36582. var faceColors = options.faceColors;
  36583. // default face colors and UV if undefined
  36584. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36585. var ringNb = (hasRings) ? subdivisions : 1;
  36586. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36587. var f;
  36588. for (f = 0; f < surfaceNb; f++) {
  36589. if (faceColors && faceColors[f] === undefined) {
  36590. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36591. }
  36592. }
  36593. for (f = 0; f < surfaceNb; f++) {
  36594. if (faceUV && faceUV[f] === undefined) {
  36595. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36596. }
  36597. }
  36598. var indices = new Array();
  36599. var positions = new Array();
  36600. var normals = new Array();
  36601. var uvs = new Array();
  36602. var colors = new Array();
  36603. var angle_step = Math.PI * 2 * arc / tessellation;
  36604. var angle;
  36605. var h;
  36606. var radius;
  36607. var tan = (diameterBottom - diameterTop) / 2 / height;
  36608. var ringVertex = BABYLON.Vector3.Zero();
  36609. var ringNormal = BABYLON.Vector3.Zero();
  36610. var ringFirstVertex = BABYLON.Vector3.Zero();
  36611. var ringFirstNormal = BABYLON.Vector3.Zero();
  36612. var quadNormal = BABYLON.Vector3.Zero();
  36613. var Y = BABYLON.Axis.Y;
  36614. // positions, normals, uvs
  36615. var i;
  36616. var j;
  36617. var r;
  36618. var ringIdx = 1;
  36619. var s = 1; // surface index
  36620. var cs = 0;
  36621. var v = 0;
  36622. for (i = 0; i <= subdivisions; i++) {
  36623. h = i / subdivisions;
  36624. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36625. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36626. for (r = 0; r < ringIdx; r++) {
  36627. if (hasRings) {
  36628. s += r;
  36629. }
  36630. if (enclose) {
  36631. s += 2 * r;
  36632. }
  36633. for (j = 0; j <= tessellation; j++) {
  36634. angle = j * angle_step;
  36635. // position
  36636. ringVertex.x = Math.cos(-angle) * radius;
  36637. ringVertex.y = -height / 2 + h * height;
  36638. ringVertex.z = Math.sin(-angle) * radius;
  36639. // normal
  36640. if (diameterTop === 0 && i === subdivisions) {
  36641. // if no top cap, reuse former normals
  36642. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36643. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36644. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36645. }
  36646. else {
  36647. ringNormal.x = ringVertex.x;
  36648. ringNormal.z = ringVertex.z;
  36649. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36650. ringNormal.normalize();
  36651. }
  36652. // keep first ring vertex values for enclose
  36653. if (j === 0) {
  36654. ringFirstVertex.copyFrom(ringVertex);
  36655. ringFirstNormal.copyFrom(ringNormal);
  36656. }
  36657. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36658. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36659. if (hasRings) {
  36660. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36661. }
  36662. else {
  36663. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36664. }
  36665. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36666. if (faceColors) {
  36667. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36668. }
  36669. }
  36670. // if enclose, add four vertices and their dedicated normals
  36671. if (arc !== 1 && enclose) {
  36672. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36673. positions.push(0, ringVertex.y, 0);
  36674. positions.push(0, ringVertex.y, 0);
  36675. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36676. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36677. quadNormal.normalize();
  36678. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36679. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36680. quadNormal.normalize();
  36681. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36682. if (hasRings) {
  36683. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36684. }
  36685. else {
  36686. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36687. }
  36688. uvs.push(faceUV[s + 1].x, v);
  36689. uvs.push(faceUV[s + 1].z, v);
  36690. if (hasRings) {
  36691. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36692. }
  36693. else {
  36694. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36695. }
  36696. uvs.push(faceUV[s + 2].x, v);
  36697. uvs.push(faceUV[s + 2].z, v);
  36698. if (faceColors) {
  36699. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36700. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36701. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36702. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36703. }
  36704. }
  36705. if (cs !== s) {
  36706. cs = s;
  36707. }
  36708. }
  36709. }
  36710. // indices
  36711. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36712. var s;
  36713. i = 0;
  36714. for (s = 0; s < subdivisions; s++) {
  36715. var i0 = 0;
  36716. var i1 = 0;
  36717. var i2 = 0;
  36718. var i3 = 0;
  36719. for (j = 0; j < tessellation; j++) {
  36720. i0 = i * (e + 1) + j;
  36721. i1 = (i + 1) * (e + 1) + j;
  36722. i2 = i * (e + 1) + (j + 1);
  36723. i3 = (i + 1) * (e + 1) + (j + 1);
  36724. indices.push(i0, i1, i2);
  36725. indices.push(i3, i2, i1);
  36726. }
  36727. if (arc !== 1 && enclose) { // if enclose, add two quads
  36728. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36729. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36730. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36731. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36732. }
  36733. i = (hasRings) ? (i + 2) : (i + 1);
  36734. }
  36735. // Caps
  36736. var createCylinderCap = function (isTop) {
  36737. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36738. if (radius === 0) {
  36739. return;
  36740. }
  36741. // Cap positions, normals & uvs
  36742. var angle;
  36743. var circleVector;
  36744. var i;
  36745. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36746. var c = null;
  36747. if (faceColors) {
  36748. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36749. }
  36750. // cap center
  36751. var vbase = positions.length / 3;
  36752. var offset = isTop ? height / 2 : -height / 2;
  36753. var center = new BABYLON.Vector3(0, offset, 0);
  36754. positions.push(center.x, center.y, center.z);
  36755. normals.push(0, isTop ? 1 : -1, 0);
  36756. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36757. if (c) {
  36758. colors.push(c.r, c.g, c.b, c.a);
  36759. }
  36760. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36761. for (i = 0; i <= tessellation; i++) {
  36762. angle = Math.PI * 2 * i * arc / tessellation;
  36763. var cos = Math.cos(-angle);
  36764. var sin = Math.sin(-angle);
  36765. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36766. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36767. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36768. normals.push(0, isTop ? 1 : -1, 0);
  36769. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36770. if (c) {
  36771. colors.push(c.r, c.g, c.b, c.a);
  36772. }
  36773. }
  36774. // Cap indices
  36775. for (i = 0; i < tessellation; i++) {
  36776. if (!isTop) {
  36777. indices.push(vbase);
  36778. indices.push(vbase + (i + 1));
  36779. indices.push(vbase + (i + 2));
  36780. }
  36781. else {
  36782. indices.push(vbase);
  36783. indices.push(vbase + (i + 2));
  36784. indices.push(vbase + (i + 1));
  36785. }
  36786. }
  36787. };
  36788. // add caps to geometry
  36789. createCylinderCap(false);
  36790. createCylinderCap(true);
  36791. // Sides
  36792. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36793. var vertexData = new VertexData();
  36794. vertexData.indices = indices;
  36795. vertexData.positions = positions;
  36796. vertexData.normals = normals;
  36797. vertexData.uvs = uvs;
  36798. if (faceColors) {
  36799. vertexData.colors = colors;
  36800. }
  36801. return vertexData;
  36802. };
  36803. /**
  36804. * Creates the VertexData for a torus
  36805. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36806. * * diameter the diameter of the torus, optional default 1
  36807. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36808. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36809. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36810. * * 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)
  36811. * * 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)
  36812. * @returns the VertexData of the torus
  36813. */
  36814. VertexData.CreateTorus = function (options) {
  36815. var indices = [];
  36816. var positions = [];
  36817. var normals = [];
  36818. var uvs = [];
  36819. var diameter = options.diameter || 1;
  36820. var thickness = options.thickness || 0.5;
  36821. var tessellation = options.tessellation || 16;
  36822. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36823. var stride = tessellation + 1;
  36824. for (var i = 0; i <= tessellation; i++) {
  36825. var u = i / tessellation;
  36826. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36827. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36828. for (var j = 0; j <= tessellation; j++) {
  36829. var v = 1 - j / tessellation;
  36830. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36831. var dx = Math.cos(innerAngle);
  36832. var dy = Math.sin(innerAngle);
  36833. // Create a vertex.
  36834. var normal = new BABYLON.Vector3(dx, dy, 0);
  36835. var position = normal.scale(thickness / 2);
  36836. var textureCoordinate = new BABYLON.Vector2(u, v);
  36837. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36838. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36839. positions.push(position.x, position.y, position.z);
  36840. normals.push(normal.x, normal.y, normal.z);
  36841. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36842. // And create indices for two triangles.
  36843. var nextI = (i + 1) % stride;
  36844. var nextJ = (j + 1) % stride;
  36845. indices.push(i * stride + j);
  36846. indices.push(i * stride + nextJ);
  36847. indices.push(nextI * stride + j);
  36848. indices.push(i * stride + nextJ);
  36849. indices.push(nextI * stride + nextJ);
  36850. indices.push(nextI * stride + j);
  36851. }
  36852. }
  36853. // Sides
  36854. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36855. // Result
  36856. var vertexData = new VertexData();
  36857. vertexData.indices = indices;
  36858. vertexData.positions = positions;
  36859. vertexData.normals = normals;
  36860. vertexData.uvs = uvs;
  36861. return vertexData;
  36862. };
  36863. /**
  36864. * Creates the VertexData of the LineSystem
  36865. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36866. * - lines an array of lines, each line being an array of successive Vector3
  36867. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36868. * @returns the VertexData of the LineSystem
  36869. */
  36870. VertexData.CreateLineSystem = function (options) {
  36871. var indices = [];
  36872. var positions = [];
  36873. var lines = options.lines;
  36874. var colors = options.colors;
  36875. var vertexColors = [];
  36876. var idx = 0;
  36877. for (var l = 0; l < lines.length; l++) {
  36878. var points = lines[l];
  36879. for (var index = 0; index < points.length; index++) {
  36880. positions.push(points[index].x, points[index].y, points[index].z);
  36881. if (colors) {
  36882. var color = colors[l];
  36883. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36884. }
  36885. if (index > 0) {
  36886. indices.push(idx - 1);
  36887. indices.push(idx);
  36888. }
  36889. idx++;
  36890. }
  36891. }
  36892. var vertexData = new VertexData();
  36893. vertexData.indices = indices;
  36894. vertexData.positions = positions;
  36895. if (colors) {
  36896. vertexData.colors = vertexColors;
  36897. }
  36898. return vertexData;
  36899. };
  36900. /**
  36901. * Create the VertexData for a DashedLines
  36902. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36903. * - points an array successive Vector3
  36904. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36905. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36906. * - dashNb the intended total number of dashes, optional, default 200
  36907. * @returns the VertexData for the DashedLines
  36908. */
  36909. VertexData.CreateDashedLines = function (options) {
  36910. var dashSize = options.dashSize || 3;
  36911. var gapSize = options.gapSize || 1;
  36912. var dashNb = options.dashNb || 200;
  36913. var points = options.points;
  36914. var positions = new Array();
  36915. var indices = new Array();
  36916. var curvect = BABYLON.Vector3.Zero();
  36917. var lg = 0;
  36918. var nb = 0;
  36919. var shft = 0;
  36920. var dashshft = 0;
  36921. var curshft = 0;
  36922. var idx = 0;
  36923. var i = 0;
  36924. for (i = 0; i < points.length - 1; i++) {
  36925. points[i + 1].subtractToRef(points[i], curvect);
  36926. lg += curvect.length();
  36927. }
  36928. shft = lg / dashNb;
  36929. dashshft = dashSize * shft / (dashSize + gapSize);
  36930. for (i = 0; i < points.length - 1; i++) {
  36931. points[i + 1].subtractToRef(points[i], curvect);
  36932. nb = Math.floor(curvect.length() / shft);
  36933. curvect.normalize();
  36934. for (var j = 0; j < nb; j++) {
  36935. curshft = shft * j;
  36936. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36937. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36938. indices.push(idx, idx + 1);
  36939. idx += 2;
  36940. }
  36941. }
  36942. // Result
  36943. var vertexData = new VertexData();
  36944. vertexData.positions = positions;
  36945. vertexData.indices = indices;
  36946. return vertexData;
  36947. };
  36948. /**
  36949. * Creates the VertexData for a Ground
  36950. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36951. * - width the width (x direction) of the ground, optional, default 1
  36952. * - height the height (z direction) of the ground, optional, default 1
  36953. * - subdivisions the number of subdivisions per side, optional, default 1
  36954. * @returns the VertexData of the Ground
  36955. */
  36956. VertexData.CreateGround = function (options) {
  36957. var indices = [];
  36958. var positions = [];
  36959. var normals = [];
  36960. var uvs = [];
  36961. var row, col;
  36962. var width = options.width || 1;
  36963. var height = options.height || 1;
  36964. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  36965. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  36966. for (row = 0; row <= subdivisionsY; row++) {
  36967. for (col = 0; col <= subdivisionsX; col++) {
  36968. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  36969. var normal = new BABYLON.Vector3(0, 1.0, 0);
  36970. positions.push(position.x, position.y, position.z);
  36971. normals.push(normal.x, normal.y, normal.z);
  36972. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  36973. }
  36974. }
  36975. for (row = 0; row < subdivisionsY; row++) {
  36976. for (col = 0; col < subdivisionsX; col++) {
  36977. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36978. indices.push(col + 1 + row * (subdivisionsX + 1));
  36979. indices.push(col + row * (subdivisionsX + 1));
  36980. indices.push(col + (row + 1) * (subdivisionsX + 1));
  36981. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  36982. indices.push(col + row * (subdivisionsX + 1));
  36983. }
  36984. }
  36985. // Result
  36986. var vertexData = new VertexData();
  36987. vertexData.indices = indices;
  36988. vertexData.positions = positions;
  36989. vertexData.normals = normals;
  36990. vertexData.uvs = uvs;
  36991. return vertexData;
  36992. };
  36993. /**
  36994. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  36995. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  36996. * * xmin the ground minimum X coordinate, optional, default -1
  36997. * * zmin the ground minimum Z coordinate, optional, default -1
  36998. * * xmax the ground maximum X coordinate, optional, default 1
  36999. * * zmax the ground maximum Z coordinate, optional, default 1
  37000. * * 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}
  37001. * * 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}
  37002. * @returns the VertexData of the TiledGround
  37003. */
  37004. VertexData.CreateTiledGround = function (options) {
  37005. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37006. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37007. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37008. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37009. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37010. var precision = options.precision || { w: 1, h: 1 };
  37011. var indices = new Array();
  37012. var positions = new Array();
  37013. var normals = new Array();
  37014. var uvs = new Array();
  37015. var row, col, tileRow, tileCol;
  37016. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37017. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37018. precision.w = (precision.w < 1) ? 1 : precision.w;
  37019. precision.h = (precision.h < 1) ? 1 : precision.h;
  37020. var tileSize = {
  37021. 'w': (xmax - xmin) / subdivisions.w,
  37022. 'h': (zmax - zmin) / subdivisions.h
  37023. };
  37024. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37025. // Indices
  37026. var base = positions.length / 3;
  37027. var rowLength = precision.w + 1;
  37028. for (row = 0; row < precision.h; row++) {
  37029. for (col = 0; col < precision.w; col++) {
  37030. var square = [
  37031. base + col + row * rowLength,
  37032. base + (col + 1) + row * rowLength,
  37033. base + (col + 1) + (row + 1) * rowLength,
  37034. base + col + (row + 1) * rowLength
  37035. ];
  37036. indices.push(square[1]);
  37037. indices.push(square[2]);
  37038. indices.push(square[3]);
  37039. indices.push(square[0]);
  37040. indices.push(square[1]);
  37041. indices.push(square[3]);
  37042. }
  37043. }
  37044. // Position, normals and uvs
  37045. var position = BABYLON.Vector3.Zero();
  37046. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37047. for (row = 0; row <= precision.h; row++) {
  37048. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37049. for (col = 0; col <= precision.w; col++) {
  37050. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37051. position.y = 0;
  37052. positions.push(position.x, position.y, position.z);
  37053. normals.push(normal.x, normal.y, normal.z);
  37054. uvs.push(col / precision.w, row / precision.h);
  37055. }
  37056. }
  37057. }
  37058. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37059. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37060. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37061. }
  37062. }
  37063. // Result
  37064. var vertexData = new VertexData();
  37065. vertexData.indices = indices;
  37066. vertexData.positions = positions;
  37067. vertexData.normals = normals;
  37068. vertexData.uvs = uvs;
  37069. return vertexData;
  37070. };
  37071. /**
  37072. * Creates the VertexData of the Ground designed from a heightmap
  37073. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37074. * * width the width (x direction) of the ground
  37075. * * height the height (z direction) of the ground
  37076. * * subdivisions the number of subdivisions per side
  37077. * * minHeight the minimum altitude on the ground, optional, default 0
  37078. * * maxHeight the maximum altitude on the ground, optional default 1
  37079. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37080. * * buffer the array holding the image color data
  37081. * * bufferWidth the width of image
  37082. * * bufferHeight the height of image
  37083. * @returns the VertexData of the Ground designed from a heightmap
  37084. */
  37085. VertexData.CreateGroundFromHeightMap = function (options) {
  37086. var indices = [];
  37087. var positions = [];
  37088. var normals = [];
  37089. var uvs = [];
  37090. var row, col;
  37091. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37092. // Vertices
  37093. for (row = 0; row <= options.subdivisions; row++) {
  37094. for (col = 0; col <= options.subdivisions; col++) {
  37095. 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));
  37096. // Compute height
  37097. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37098. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37099. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37100. var r = options.buffer[pos] / 255.0;
  37101. var g = options.buffer[pos + 1] / 255.0;
  37102. var b = options.buffer[pos + 2] / 255.0;
  37103. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37104. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37105. // Add vertex
  37106. positions.push(position.x, position.y, position.z);
  37107. normals.push(0, 0, 0);
  37108. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37109. }
  37110. }
  37111. // Indices
  37112. for (row = 0; row < options.subdivisions; row++) {
  37113. for (col = 0; col < options.subdivisions; col++) {
  37114. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37115. indices.push(col + 1 + row * (options.subdivisions + 1));
  37116. indices.push(col + row * (options.subdivisions + 1));
  37117. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37118. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37119. indices.push(col + row * (options.subdivisions + 1));
  37120. }
  37121. }
  37122. // Normals
  37123. VertexData.ComputeNormals(positions, indices, normals);
  37124. // Result
  37125. var vertexData = new VertexData();
  37126. vertexData.indices = indices;
  37127. vertexData.positions = positions;
  37128. vertexData.normals = normals;
  37129. vertexData.uvs = uvs;
  37130. return vertexData;
  37131. };
  37132. /**
  37133. * Creates the VertexData for a Plane
  37134. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37135. * * size sets the width and height of the plane to the value of size, optional default 1
  37136. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37137. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37138. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37139. * * 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)
  37140. * * 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)
  37141. * @returns the VertexData of the box
  37142. */
  37143. VertexData.CreatePlane = function (options) {
  37144. var indices = [];
  37145. var positions = [];
  37146. var normals = [];
  37147. var uvs = [];
  37148. var width = options.width || options.size || 1;
  37149. var height = options.height || options.size || 1;
  37150. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37151. // Vertices
  37152. var halfWidth = width / 2.0;
  37153. var halfHeight = height / 2.0;
  37154. positions.push(-halfWidth, -halfHeight, 0);
  37155. normals.push(0, 0, -1.0);
  37156. uvs.push(0.0, 0.0);
  37157. positions.push(halfWidth, -halfHeight, 0);
  37158. normals.push(0, 0, -1.0);
  37159. uvs.push(1.0, 0.0);
  37160. positions.push(halfWidth, halfHeight, 0);
  37161. normals.push(0, 0, -1.0);
  37162. uvs.push(1.0, 1.0);
  37163. positions.push(-halfWidth, halfHeight, 0);
  37164. normals.push(0, 0, -1.0);
  37165. uvs.push(0.0, 1.0);
  37166. // Indices
  37167. indices.push(0);
  37168. indices.push(1);
  37169. indices.push(2);
  37170. indices.push(0);
  37171. indices.push(2);
  37172. indices.push(3);
  37173. // Sides
  37174. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37175. // Result
  37176. var vertexData = new VertexData();
  37177. vertexData.indices = indices;
  37178. vertexData.positions = positions;
  37179. vertexData.normals = normals;
  37180. vertexData.uvs = uvs;
  37181. return vertexData;
  37182. };
  37183. /**
  37184. * Creates the VertexData of the Disc or regular Polygon
  37185. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37186. * * radius the radius of the disc, optional default 0.5
  37187. * * tessellation the number of polygon sides, optional, default 64
  37188. * * 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
  37189. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37190. * * 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)
  37191. * * 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)
  37192. * @returns the VertexData of the box
  37193. */
  37194. VertexData.CreateDisc = function (options) {
  37195. var positions = new Array();
  37196. var indices = new Array();
  37197. var normals = new Array();
  37198. var uvs = new Array();
  37199. var radius = options.radius || 0.5;
  37200. var tessellation = options.tessellation || 64;
  37201. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37203. // positions and uvs
  37204. positions.push(0, 0, 0); // disc center first
  37205. uvs.push(0.5, 0.5);
  37206. var theta = Math.PI * 2 * arc;
  37207. var step = theta / tessellation;
  37208. for (var a = 0; a < theta; a += step) {
  37209. var x = Math.cos(a);
  37210. var y = Math.sin(a);
  37211. var u = (x + 1) / 2;
  37212. var v = (1 - y) / 2;
  37213. positions.push(radius * x, radius * y, 0);
  37214. uvs.push(u, v);
  37215. }
  37216. if (arc === 1) {
  37217. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37218. uvs.push(uvs[2], uvs[3]);
  37219. }
  37220. //indices
  37221. var vertexNb = positions.length / 3;
  37222. for (var i = 1; i < vertexNb - 1; i++) {
  37223. indices.push(i + 1, 0, i);
  37224. }
  37225. // result
  37226. VertexData.ComputeNormals(positions, indices, normals);
  37227. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37228. var vertexData = new VertexData();
  37229. vertexData.indices = indices;
  37230. vertexData.positions = positions;
  37231. vertexData.normals = normals;
  37232. vertexData.uvs = uvs;
  37233. return vertexData;
  37234. };
  37235. /**
  37236. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37237. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37238. * @param polygon a mesh built from polygonTriangulation.build()
  37239. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37240. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37241. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37242. * @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)
  37243. * @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)
  37244. * @returns the VertexData of the Polygon
  37245. */
  37246. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37247. var faceUV = fUV || new Array(3);
  37248. var faceColors = fColors;
  37249. var colors = [];
  37250. // default face colors and UV if undefined
  37251. for (var f = 0; f < 3; f++) {
  37252. if (faceUV[f] === undefined) {
  37253. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37254. }
  37255. if (faceColors && faceColors[f] === undefined) {
  37256. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37257. }
  37258. }
  37259. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37260. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37261. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37262. var indices = polygon.getIndices();
  37263. // set face colours and textures
  37264. var idx = 0;
  37265. var face = 0;
  37266. for (var index = 0; index < normals.length; index += 3) {
  37267. //Edge Face no. 1
  37268. if (Math.abs(normals[index + 1]) < 0.001) {
  37269. face = 1;
  37270. }
  37271. //Top Face no. 0
  37272. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37273. face = 0;
  37274. }
  37275. //Bottom Face no. 2
  37276. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37277. face = 2;
  37278. }
  37279. idx = index / 3;
  37280. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37281. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37282. if (faceColors) {
  37283. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37284. }
  37285. }
  37286. // sides
  37287. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37288. // Result
  37289. var vertexData = new VertexData();
  37290. vertexData.indices = indices;
  37291. vertexData.positions = positions;
  37292. vertexData.normals = normals;
  37293. vertexData.uvs = uvs;
  37294. if (faceColors) {
  37295. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37296. vertexData.colors = totalColors;
  37297. }
  37298. return vertexData;
  37299. };
  37300. /**
  37301. * Creates the VertexData of the IcoSphere
  37302. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37303. * * radius the radius of the IcoSphere, optional default 1
  37304. * * radiusX allows stretching in the x direction, optional, default radius
  37305. * * radiusY allows stretching in the y direction, optional, default radius
  37306. * * radiusZ allows stretching in the z direction, optional, default radius
  37307. * * flat when true creates a flat shaded mesh, optional, default true
  37308. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37309. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37310. * * 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)
  37311. * * 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)
  37312. * @returns the VertexData of the IcoSphere
  37313. */
  37314. VertexData.CreateIcoSphere = function (options) {
  37315. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37316. var radius = options.radius || 1;
  37317. var flat = (options.flat === undefined) ? true : options.flat;
  37318. var subdivisions = options.subdivisions || 4;
  37319. var radiusX = options.radiusX || radius;
  37320. var radiusY = options.radiusY || radius;
  37321. var radiusZ = options.radiusZ || radius;
  37322. var t = (1 + Math.sqrt(5)) / 2;
  37323. // 12 vertex x,y,z
  37324. var ico_vertices = [
  37325. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37326. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37327. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37328. ];
  37329. // index of 3 vertex makes a face of icopshere
  37330. var ico_indices = [
  37331. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37332. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37333. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37334. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37335. ];
  37336. // vertex for uv have aliased position, not for UV
  37337. var vertices_unalias_id = [
  37338. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37339. // vertex alias
  37340. 0,
  37341. 2,
  37342. 3,
  37343. 3,
  37344. 3,
  37345. 4,
  37346. 7,
  37347. 8,
  37348. 9,
  37349. 9,
  37350. 10,
  37351. 11 // 23: B + 12
  37352. ];
  37353. // uv as integer step (not pixels !)
  37354. var ico_vertexuv = [
  37355. 5, 1, 3, 1, 6, 4, 0, 0,
  37356. 5, 3, 4, 2, 2, 2, 4, 0,
  37357. 2, 0, 1, 1, 6, 0, 6, 2,
  37358. // vertex alias (for same vertex on different faces)
  37359. 0, 4,
  37360. 3, 3,
  37361. 4, 4,
  37362. 3, 1,
  37363. 4, 2,
  37364. 4, 4,
  37365. 0, 2,
  37366. 1, 1,
  37367. 2, 2,
  37368. 3, 3,
  37369. 1, 3,
  37370. 2, 4 // 23: B + 12
  37371. ];
  37372. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37373. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37374. // First island of uv mapping
  37375. // v = 4h 3+ 2
  37376. // v = 3h 9+ 4
  37377. // v = 2h 9+ 5 B
  37378. // v = 1h 9 1 0
  37379. // v = 0h 3 8 7 A
  37380. // u = 0 1 2 3 4 5 6 *a
  37381. // Second island of uv mapping
  37382. // v = 4h 0+ B+ 4+
  37383. // v = 3h A+ 2+
  37384. // v = 2h 7+ 6 3+
  37385. // v = 1h 8+ 3+
  37386. // v = 0h
  37387. // u = 0 1 2 3 4 5 6 *a
  37388. // Face layout on texture UV mapping
  37389. // ============
  37390. // \ 4 /\ 16 / ======
  37391. // \ / \ / /\ 11 /
  37392. // \/ 7 \/ / \ /
  37393. // ======= / 10 \/
  37394. // /\ 17 /\ =======
  37395. // / \ / \ \ 15 /\
  37396. // / 8 \/ 12 \ \ / \
  37397. // ============ \/ 6 \
  37398. // \ 18 /\ ============
  37399. // \ / \ \ 5 /\ 0 /
  37400. // \/ 13 \ \ / \ /
  37401. // ======= \/ 1 \/
  37402. // =============
  37403. // /\ 19 /\ 2 /\
  37404. // / \ / \ / \
  37405. // / 14 \/ 9 \/ 3 \
  37406. // ===================
  37407. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37408. var ustep = 138 / 1024;
  37409. var vstep = 239 / 1024;
  37410. var uoffset = 60 / 1024;
  37411. var voffset = 26 / 1024;
  37412. // Second island should have margin, not to touch the first island
  37413. // avoid any borderline artefact in pixel rounding
  37414. var island_u_offset = -40 / 1024;
  37415. var island_v_offset = +20 / 1024;
  37416. // face is either island 0 or 1 :
  37417. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37418. var island = [
  37419. 0, 0, 0, 0, 1,
  37420. 0, 0, 1, 1, 0,
  37421. 0, 0, 1, 1, 0,
  37422. 0, 1, 1, 1, 0 // 15 - 19
  37423. ];
  37424. var indices = new Array();
  37425. var positions = new Array();
  37426. var normals = new Array();
  37427. var uvs = new Array();
  37428. var current_indice = 0;
  37429. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37430. var face_vertex_pos = new Array(3);
  37431. var face_vertex_uv = new Array(3);
  37432. var v012;
  37433. for (v012 = 0; v012 < 3; v012++) {
  37434. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37435. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37436. }
  37437. // create all with normals
  37438. for (var face = 0; face < 20; face++) {
  37439. // 3 vertex per face
  37440. for (v012 = 0; v012 < 3; v012++) {
  37441. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37442. var v_id = ico_indices[3 * face + v012];
  37443. // vertex have 3D position (x,y,z)
  37444. 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]);
  37445. // Normalize to get normal, then scale to radius
  37446. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37447. // uv Coordinates from vertex ID
  37448. 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);
  37449. }
  37450. // Subdivide the face (interpolate pos, norm, uv)
  37451. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37452. // - norm is linear interpolation of vertex corner normal
  37453. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37454. // - uv is linear interpolation
  37455. //
  37456. // Topology is as below for sub-divide by 2
  37457. // vertex shown as v0,v1,v2
  37458. // interp index is i1 to progress in range [v0,v1[
  37459. // interp index is i2 to progress in range [v0,v2[
  37460. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37461. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37462. //
  37463. //
  37464. // i2 v2
  37465. // ^ ^
  37466. // / / \
  37467. // / / \
  37468. // / / \
  37469. // / / (0,1) \
  37470. // / #---------\
  37471. // / / \ (0,0)'/ \
  37472. // / / \ / \
  37473. // / / \ / \
  37474. // / / (0,0) \ / (1,0) \
  37475. // / #---------#---------\
  37476. // v0 v1
  37477. //
  37478. // --------------------> i1
  37479. //
  37480. // interp of (i1,i2):
  37481. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37482. // along i1 : lerp(x0,x1, i1/(S-i2))
  37483. //
  37484. // centroid of triangle is needed to get help normal computation
  37485. // (c1,c2) are used for centroid location
  37486. var interp_vertex = function (i1, i2, c1, c2) {
  37487. // vertex is interpolated from
  37488. // - face_vertex_pos[0..2]
  37489. // - face_vertex_uv[0..2]
  37490. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37491. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37492. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37493. pos_interp.normalize();
  37494. var vertex_normal;
  37495. if (flat) {
  37496. // in flat mode, recalculate normal as face centroid normal
  37497. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37498. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37499. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37500. }
  37501. else {
  37502. // in smooth mode, recalculate normal from each single vertex position
  37503. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37504. }
  37505. // Vertex normal need correction due to X,Y,Z radius scaling
  37506. vertex_normal.x /= radiusX;
  37507. vertex_normal.y /= radiusY;
  37508. vertex_normal.z /= radiusZ;
  37509. vertex_normal.normalize();
  37510. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37511. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37512. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37513. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37514. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37515. uvs.push(uv_interp.x, uv_interp.y);
  37516. // push each vertex has member of a face
  37517. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37518. indices.push(current_indice);
  37519. current_indice++;
  37520. };
  37521. for (var i2 = 0; i2 < subdivisions; i2++) {
  37522. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37523. // face : (i1,i2) for /\ :
  37524. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37525. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37526. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37527. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37528. if (i1 + i2 + 1 < subdivisions) {
  37529. // face : (i1,i2)' for \/ :
  37530. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37531. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37532. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37533. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37534. }
  37535. }
  37536. }
  37537. }
  37538. // Sides
  37539. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37540. // Result
  37541. var vertexData = new VertexData();
  37542. vertexData.indices = indices;
  37543. vertexData.positions = positions;
  37544. vertexData.normals = normals;
  37545. vertexData.uvs = uvs;
  37546. return vertexData;
  37547. };
  37548. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37549. /**
  37550. * Creates the VertexData for a Polyhedron
  37551. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37552. * * type provided types are:
  37553. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37554. * * 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)
  37555. * * size the size of the IcoSphere, optional default 1
  37556. * * sizeX allows stretching in the x direction, optional, default size
  37557. * * sizeY allows stretching in the y direction, optional, default size
  37558. * * sizeZ allows stretching in the z direction, optional, default size
  37559. * * 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
  37560. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37561. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37562. * * flat when true creates a flat shaded mesh, optional, default true
  37563. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37564. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37565. * * 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)
  37566. * * 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)
  37567. * @returns the VertexData of the Polyhedron
  37568. */
  37569. VertexData.CreatePolyhedron = function (options) {
  37570. // provided polyhedron types :
  37571. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37572. // 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)
  37573. var polyhedra = [];
  37574. 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]] };
  37575. 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]] };
  37576. polyhedra[2] = {
  37577. 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]],
  37578. 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]]
  37579. };
  37580. polyhedra[3] = {
  37581. 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]],
  37582. 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]]
  37583. };
  37584. polyhedra[4] = {
  37585. 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]],
  37586. 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]]
  37587. };
  37588. 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]] };
  37589. 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]] };
  37590. 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]] };
  37591. 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]] };
  37592. 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]] };
  37593. 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]] };
  37594. 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]] };
  37595. 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]] };
  37596. 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]] };
  37597. polyhedra[14] = {
  37598. 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]],
  37599. 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]]
  37600. };
  37601. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37602. var size = options.size;
  37603. var sizeX = options.sizeX || size || 1;
  37604. var sizeY = options.sizeY || size || 1;
  37605. var sizeZ = options.sizeZ || size || 1;
  37606. var data = options.custom || polyhedra[type];
  37607. var nbfaces = data.face.length;
  37608. var faceUV = options.faceUV || new Array(nbfaces);
  37609. var faceColors = options.faceColors;
  37610. var flat = (options.flat === undefined) ? true : options.flat;
  37611. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37612. var positions = new Array();
  37613. var indices = new Array();
  37614. var normals = new Array();
  37615. var uvs = new Array();
  37616. var colors = new Array();
  37617. var index = 0;
  37618. var faceIdx = 0; // face cursor in the array "indexes"
  37619. var indexes = new Array();
  37620. var i = 0;
  37621. var f = 0;
  37622. var u, v, ang, x, y, tmp;
  37623. // default face colors and UV if undefined
  37624. if (flat) {
  37625. for (f = 0; f < nbfaces; f++) {
  37626. if (faceColors && faceColors[f] === undefined) {
  37627. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37628. }
  37629. if (faceUV && faceUV[f] === undefined) {
  37630. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37631. }
  37632. }
  37633. }
  37634. if (!flat) {
  37635. for (i = 0; i < data.vertex.length; i++) {
  37636. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37637. uvs.push(0, 0);
  37638. }
  37639. for (f = 0; f < nbfaces; f++) {
  37640. for (i = 0; i < data.face[f].length - 2; i++) {
  37641. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37642. }
  37643. }
  37644. }
  37645. else {
  37646. for (f = 0; f < nbfaces; f++) {
  37647. var fl = data.face[f].length; // number of vertices of the current face
  37648. ang = 2 * Math.PI / fl;
  37649. x = 0.5 * Math.tan(ang / 2);
  37650. y = 0.5;
  37651. // positions, uvs, colors
  37652. for (i = 0; i < fl; i++) {
  37653. // positions
  37654. 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);
  37655. indexes.push(index);
  37656. index++;
  37657. // uvs
  37658. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37659. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37660. uvs.push(u, v);
  37661. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37662. y = x * Math.sin(ang) + y * Math.cos(ang);
  37663. x = tmp;
  37664. // colors
  37665. if (faceColors) {
  37666. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37667. }
  37668. }
  37669. // indices from indexes
  37670. for (i = 0; i < fl - 2; i++) {
  37671. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37672. }
  37673. faceIdx += fl;
  37674. }
  37675. }
  37676. VertexData.ComputeNormals(positions, indices, normals);
  37677. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37678. var vertexData = new VertexData();
  37679. vertexData.positions = positions;
  37680. vertexData.indices = indices;
  37681. vertexData.normals = normals;
  37682. vertexData.uvs = uvs;
  37683. if (faceColors && flat) {
  37684. vertexData.colors = colors;
  37685. }
  37686. return vertexData;
  37687. };
  37688. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37689. /**
  37690. * Creates the VertexData for a TorusKnot
  37691. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37692. * * radius the radius of the torus knot, optional, default 2
  37693. * * tube the thickness of the tube, optional, default 0.5
  37694. * * radialSegments the number of sides on each tube segments, optional, default 32
  37695. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37696. * * p the number of windings around the z axis, optional, default 2
  37697. * * q the number of windings around the x axis, optional, default 3
  37698. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37699. * * 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)
  37700. * * 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)
  37701. * @returns the VertexData of the Torus Knot
  37702. */
  37703. VertexData.CreateTorusKnot = function (options) {
  37704. var indices = new Array();
  37705. var positions = new Array();
  37706. var normals = new Array();
  37707. var uvs = new Array();
  37708. var radius = options.radius || 2;
  37709. var tube = options.tube || 0.5;
  37710. var radialSegments = options.radialSegments || 32;
  37711. var tubularSegments = options.tubularSegments || 32;
  37712. var p = options.p || 2;
  37713. var q = options.q || 3;
  37714. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37715. // Helper
  37716. var getPos = function (angle) {
  37717. var cu = Math.cos(angle);
  37718. var su = Math.sin(angle);
  37719. var quOverP = q / p * angle;
  37720. var cs = Math.cos(quOverP);
  37721. var tx = radius * (2 + cs) * 0.5 * cu;
  37722. var ty = radius * (2 + cs) * su * 0.5;
  37723. var tz = radius * Math.sin(quOverP) * 0.5;
  37724. return new BABYLON.Vector3(tx, ty, tz);
  37725. };
  37726. // Vertices
  37727. var i;
  37728. var j;
  37729. for (i = 0; i <= radialSegments; i++) {
  37730. var modI = i % radialSegments;
  37731. var u = modI / radialSegments * 2 * p * Math.PI;
  37732. var p1 = getPos(u);
  37733. var p2 = getPos(u + 0.01);
  37734. var tang = p2.subtract(p1);
  37735. var n = p2.add(p1);
  37736. var bitan = BABYLON.Vector3.Cross(tang, n);
  37737. n = BABYLON.Vector3.Cross(bitan, tang);
  37738. bitan.normalize();
  37739. n.normalize();
  37740. for (j = 0; j < tubularSegments; j++) {
  37741. var modJ = j % tubularSegments;
  37742. var v = modJ / tubularSegments * 2 * Math.PI;
  37743. var cx = -tube * Math.cos(v);
  37744. var cy = tube * Math.sin(v);
  37745. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37746. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37747. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37748. uvs.push(i / radialSegments);
  37749. uvs.push(j / tubularSegments);
  37750. }
  37751. }
  37752. for (i = 0; i < radialSegments; i++) {
  37753. for (j = 0; j < tubularSegments; j++) {
  37754. var jNext = (j + 1) % tubularSegments;
  37755. var a = i * tubularSegments + j;
  37756. var b = (i + 1) * tubularSegments + j;
  37757. var c = (i + 1) * tubularSegments + jNext;
  37758. var d = i * tubularSegments + jNext;
  37759. indices.push(d);
  37760. indices.push(b);
  37761. indices.push(a);
  37762. indices.push(d);
  37763. indices.push(c);
  37764. indices.push(b);
  37765. }
  37766. }
  37767. // Normals
  37768. VertexData.ComputeNormals(positions, indices, normals);
  37769. // Sides
  37770. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37771. // Result
  37772. var vertexData = new VertexData();
  37773. vertexData.indices = indices;
  37774. vertexData.positions = positions;
  37775. vertexData.normals = normals;
  37776. vertexData.uvs = uvs;
  37777. return vertexData;
  37778. };
  37779. // Tools
  37780. /**
  37781. * Compute normals for given positions and indices
  37782. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37783. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37784. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37785. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37786. * * facetNormals : optional array of facet normals (vector3)
  37787. * * facetPositions : optional array of facet positions (vector3)
  37788. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37789. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37790. * * bInfo : optional bounding info, required for facetPartitioning computation
  37791. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37792. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37793. * * useRightHandedSystem: optional boolean to for right handed system computation
  37794. * * depthSort : optional boolean to enable the facet depth sort computation
  37795. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37796. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37797. */
  37798. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37799. // temporary scalar variables
  37800. var index = 0; // facet index
  37801. var p1p2x = 0.0; // p1p2 vector x coordinate
  37802. var p1p2y = 0.0; // p1p2 vector y coordinate
  37803. var p1p2z = 0.0; // p1p2 vector z coordinate
  37804. var p3p2x = 0.0; // p3p2 vector x coordinate
  37805. var p3p2y = 0.0; // p3p2 vector y coordinate
  37806. var p3p2z = 0.0; // p3p2 vector z coordinate
  37807. var faceNormalx = 0.0; // facet normal x coordinate
  37808. var faceNormaly = 0.0; // facet normal y coordinate
  37809. var faceNormalz = 0.0; // facet normal z coordinate
  37810. var length = 0.0; // facet normal length before normalization
  37811. var v1x = 0; // vector1 x index in the positions array
  37812. var v1y = 0; // vector1 y index in the positions array
  37813. var v1z = 0; // vector1 z index in the positions array
  37814. var v2x = 0; // vector2 x index in the positions array
  37815. var v2y = 0; // vector2 y index in the positions array
  37816. var v2z = 0; // vector2 z index in the positions array
  37817. var v3x = 0; // vector3 x index in the positions array
  37818. var v3y = 0; // vector3 y index in the positions array
  37819. var v3z = 0; // vector3 z index in the positions array
  37820. var computeFacetNormals = false;
  37821. var computeFacetPositions = false;
  37822. var computeFacetPartitioning = false;
  37823. var computeDepthSort = false;
  37824. var faceNormalSign = 1;
  37825. var ratio = 0;
  37826. var distanceTo = null;
  37827. if (options) {
  37828. computeFacetNormals = (options.facetNormals) ? true : false;
  37829. computeFacetPositions = (options.facetPositions) ? true : false;
  37830. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37831. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37832. ratio = options.ratio || 0;
  37833. computeDepthSort = (options.depthSort) ? true : false;
  37834. distanceTo = (options.distanceTo);
  37835. if (computeDepthSort) {
  37836. if (distanceTo === undefined) {
  37837. distanceTo = BABYLON.Vector3.Zero();
  37838. }
  37839. var depthSortedFacets = options.depthSortedFacets;
  37840. }
  37841. }
  37842. // facetPartitioning reinit if needed
  37843. var xSubRatio = 0;
  37844. var ySubRatio = 0;
  37845. var zSubRatio = 0;
  37846. var subSq = 0;
  37847. if (computeFacetPartitioning && options && options.bbSize) {
  37848. var ox = 0; // X partitioning index for facet position
  37849. var oy = 0; // Y partinioning index for facet position
  37850. var oz = 0; // Z partinioning index for facet position
  37851. var b1x = 0; // X partitioning index for facet v1 vertex
  37852. var b1y = 0; // Y partitioning index for facet v1 vertex
  37853. var b1z = 0; // z partitioning index for facet v1 vertex
  37854. var b2x = 0; // X partitioning index for facet v2 vertex
  37855. var b2y = 0; // Y partitioning index for facet v2 vertex
  37856. var b2z = 0; // Z partitioning index for facet v2 vertex
  37857. var b3x = 0; // X partitioning index for facet v3 vertex
  37858. var b3y = 0; // Y partitioning index for facet v3 vertex
  37859. var b3z = 0; // Z partitioning index for facet v3 vertex
  37860. var block_idx_o = 0; // facet barycenter block index
  37861. var block_idx_v1 = 0; // v1 vertex block index
  37862. var block_idx_v2 = 0; // v2 vertex block index
  37863. var block_idx_v3 = 0; // v3 vertex block index
  37864. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37865. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37866. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37867. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37868. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37869. subSq = options.subDiv.max * options.subDiv.max;
  37870. options.facetPartitioning.length = 0;
  37871. }
  37872. // reset the normals
  37873. for (index = 0; index < positions.length; index++) {
  37874. normals[index] = 0.0;
  37875. }
  37876. // Loop : 1 indice triplet = 1 facet
  37877. var nbFaces = (indices.length / 3) | 0;
  37878. for (index = 0; index < nbFaces; index++) {
  37879. // get the indexes of the coordinates of each vertex of the facet
  37880. v1x = indices[index * 3] * 3;
  37881. v1y = v1x + 1;
  37882. v1z = v1x + 2;
  37883. v2x = indices[index * 3 + 1] * 3;
  37884. v2y = v2x + 1;
  37885. v2z = v2x + 2;
  37886. v3x = indices[index * 3 + 2] * 3;
  37887. v3y = v3x + 1;
  37888. v3z = v3x + 2;
  37889. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37890. p1p2y = positions[v1y] - positions[v2y];
  37891. p1p2z = positions[v1z] - positions[v2z];
  37892. p3p2x = positions[v3x] - positions[v2x];
  37893. p3p2y = positions[v3y] - positions[v2y];
  37894. p3p2z = positions[v3z] - positions[v2z];
  37895. // compute the face normal with the cross product
  37896. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37897. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37898. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37899. // normalize this normal and store it in the array facetData
  37900. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37901. length = (length === 0) ? 1.0 : length;
  37902. faceNormalx /= length;
  37903. faceNormaly /= length;
  37904. faceNormalz /= length;
  37905. if (computeFacetNormals && options) {
  37906. options.facetNormals[index].x = faceNormalx;
  37907. options.facetNormals[index].y = faceNormaly;
  37908. options.facetNormals[index].z = faceNormalz;
  37909. }
  37910. if (computeFacetPositions && options) {
  37911. // compute and the facet barycenter coordinates in the array facetPositions
  37912. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37913. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37914. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37915. }
  37916. if (computeFacetPartitioning && options) {
  37917. // store the facet indexes in arrays in the main facetPartitioning array :
  37918. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37919. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37920. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37921. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37922. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37923. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37924. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37925. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37926. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37927. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37928. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37929. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37930. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37931. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37932. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37933. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37934. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37935. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37936. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37937. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37938. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37939. // push each facet index in each block containing the vertex
  37940. options.facetPartitioning[block_idx_v1].push(index);
  37941. if (block_idx_v2 != block_idx_v1) {
  37942. options.facetPartitioning[block_idx_v2].push(index);
  37943. }
  37944. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37945. options.facetPartitioning[block_idx_v3].push(index);
  37946. }
  37947. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  37948. options.facetPartitioning[block_idx_o].push(index);
  37949. }
  37950. }
  37951. if (computeDepthSort && options && options.facetPositions) {
  37952. var dsf = depthSortedFacets[index];
  37953. dsf.ind = index * 3;
  37954. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  37955. }
  37956. // compute the normals anyway
  37957. normals[v1x] += faceNormalx; // accumulate all the normals per face
  37958. normals[v1y] += faceNormaly;
  37959. normals[v1z] += faceNormalz;
  37960. normals[v2x] += faceNormalx;
  37961. normals[v2y] += faceNormaly;
  37962. normals[v2z] += faceNormalz;
  37963. normals[v3x] += faceNormalx;
  37964. normals[v3y] += faceNormaly;
  37965. normals[v3z] += faceNormalz;
  37966. }
  37967. // last normalization of each normal
  37968. for (index = 0; index < normals.length / 3; index++) {
  37969. faceNormalx = normals[index * 3];
  37970. faceNormaly = normals[index * 3 + 1];
  37971. faceNormalz = normals[index * 3 + 2];
  37972. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37973. length = (length === 0) ? 1.0 : length;
  37974. faceNormalx /= length;
  37975. faceNormaly /= length;
  37976. faceNormalz /= length;
  37977. normals[index * 3] = faceNormalx;
  37978. normals[index * 3 + 1] = faceNormaly;
  37979. normals[index * 3 + 2] = faceNormalz;
  37980. }
  37981. };
  37982. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  37983. var li = indices.length;
  37984. var ln = normals.length;
  37985. var i;
  37986. var n;
  37987. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37988. switch (sideOrientation) {
  37989. case BABYLON.Mesh.FRONTSIDE:
  37990. // nothing changed
  37991. break;
  37992. case BABYLON.Mesh.BACKSIDE:
  37993. var tmp;
  37994. // indices
  37995. for (i = 0; i < li; i += 3) {
  37996. tmp = indices[i];
  37997. indices[i] = indices[i + 2];
  37998. indices[i + 2] = tmp;
  37999. }
  38000. // normals
  38001. for (n = 0; n < ln; n++) {
  38002. normals[n] = -normals[n];
  38003. }
  38004. break;
  38005. case BABYLON.Mesh.DOUBLESIDE:
  38006. // positions
  38007. var lp = positions.length;
  38008. var l = lp / 3;
  38009. for (var p = 0; p < lp; p++) {
  38010. positions[lp + p] = positions[p];
  38011. }
  38012. // indices
  38013. for (i = 0; i < li; i += 3) {
  38014. indices[i + li] = indices[i + 2] + l;
  38015. indices[i + 1 + li] = indices[i + 1] + l;
  38016. indices[i + 2 + li] = indices[i] + l;
  38017. }
  38018. // normals
  38019. for (n = 0; n < ln; n++) {
  38020. normals[ln + n] = -normals[n];
  38021. }
  38022. // uvs
  38023. var lu = uvs.length;
  38024. var u = 0;
  38025. for (u = 0; u < lu; u++) {
  38026. uvs[u + lu] = uvs[u];
  38027. }
  38028. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38029. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38030. u = 0;
  38031. for (i = 0; i < lu / 2; i++) {
  38032. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38033. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38034. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38035. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38036. u += 2;
  38037. }
  38038. break;
  38039. }
  38040. };
  38041. /**
  38042. * Applies VertexData created from the imported parameters to the geometry
  38043. * @param parsedVertexData the parsed data from an imported file
  38044. * @param geometry the geometry to apply the VertexData to
  38045. */
  38046. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38047. var vertexData = new VertexData();
  38048. // positions
  38049. var positions = parsedVertexData.positions;
  38050. if (positions) {
  38051. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38052. }
  38053. // normals
  38054. var normals = parsedVertexData.normals;
  38055. if (normals) {
  38056. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38057. }
  38058. // tangents
  38059. var tangents = parsedVertexData.tangents;
  38060. if (tangents) {
  38061. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38062. }
  38063. // uvs
  38064. var uvs = parsedVertexData.uvs;
  38065. if (uvs) {
  38066. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38067. }
  38068. // uv2s
  38069. var uv2s = parsedVertexData.uv2s;
  38070. if (uv2s) {
  38071. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38072. }
  38073. // uv3s
  38074. var uv3s = parsedVertexData.uv3s;
  38075. if (uv3s) {
  38076. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38077. }
  38078. // uv4s
  38079. var uv4s = parsedVertexData.uv4s;
  38080. if (uv4s) {
  38081. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38082. }
  38083. // uv5s
  38084. var uv5s = parsedVertexData.uv5s;
  38085. if (uv5s) {
  38086. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38087. }
  38088. // uv6s
  38089. var uv6s = parsedVertexData.uv6s;
  38090. if (uv6s) {
  38091. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38092. }
  38093. // colors
  38094. var colors = parsedVertexData.colors;
  38095. if (colors) {
  38096. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38097. }
  38098. // matricesIndices
  38099. var matricesIndices = parsedVertexData.matricesIndices;
  38100. if (matricesIndices) {
  38101. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38102. }
  38103. // matricesWeights
  38104. var matricesWeights = parsedVertexData.matricesWeights;
  38105. if (matricesWeights) {
  38106. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38107. }
  38108. // indices
  38109. var indices = parsedVertexData.indices;
  38110. if (indices) {
  38111. vertexData.indices = indices;
  38112. }
  38113. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38114. };
  38115. return VertexData;
  38116. }());
  38117. BABYLON.VertexData = VertexData;
  38118. })(BABYLON || (BABYLON = {}));
  38119. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38120. var BABYLON;
  38121. (function (BABYLON) {
  38122. /**
  38123. * Class used to store geometry data (vertex buffers + index buffer)
  38124. */
  38125. var Geometry = /** @class */ (function () {
  38126. /**
  38127. * Creates a new geometry
  38128. * @param id defines the unique ID
  38129. * @param scene defines the hosting scene
  38130. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38131. * @param updatable defines if geometry must be updatable (false by default)
  38132. * @param mesh defines the mesh that will be associated with the geometry
  38133. */
  38134. function Geometry(id, scene, vertexData, updatable, mesh) {
  38135. if (updatable === void 0) { updatable = false; }
  38136. if (mesh === void 0) { mesh = null; }
  38137. /**
  38138. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38139. */
  38140. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38141. this._totalVertices = 0;
  38142. this._isDisposed = false;
  38143. this._indexBufferIsUpdatable = false;
  38144. this.id = id;
  38145. this._engine = scene.getEngine();
  38146. this._meshes = [];
  38147. this._scene = scene;
  38148. //Init vertex buffer cache
  38149. this._vertexBuffers = {};
  38150. this._indices = [];
  38151. this._updatable = updatable;
  38152. // vertexData
  38153. if (vertexData) {
  38154. this.setAllVerticesData(vertexData, updatable);
  38155. }
  38156. else {
  38157. this._totalVertices = 0;
  38158. this._indices = [];
  38159. }
  38160. if (this._engine.getCaps().vertexArrayObject) {
  38161. this._vertexArrayObjects = {};
  38162. }
  38163. // applyToMesh
  38164. if (mesh) {
  38165. if (mesh.getClassName() === "LinesMesh") {
  38166. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38167. this._updateExtend();
  38168. }
  38169. this.applyToMesh(mesh);
  38170. mesh.computeWorldMatrix(true);
  38171. }
  38172. }
  38173. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38174. /**
  38175. * 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
  38176. */
  38177. get: function () {
  38178. return this._boundingBias;
  38179. },
  38180. /**
  38181. * 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
  38182. */
  38183. set: function (value) {
  38184. if (this._boundingBias && this._boundingBias.equals(value)) {
  38185. return;
  38186. }
  38187. this._boundingBias = value.clone();
  38188. this._updateBoundingInfo(true, null);
  38189. },
  38190. enumerable: true,
  38191. configurable: true
  38192. });
  38193. /**
  38194. * Static function used to attach a new empty geometry to a mesh
  38195. * @param mesh defines the mesh to attach the geometry to
  38196. * @returns the new {BABYLON.Geometry}
  38197. */
  38198. Geometry.CreateGeometryForMesh = function (mesh) {
  38199. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38200. geometry.applyToMesh(mesh);
  38201. return geometry;
  38202. };
  38203. Object.defineProperty(Geometry.prototype, "extend", {
  38204. /**
  38205. * Gets the current extend of the geometry
  38206. */
  38207. get: function () {
  38208. return this._extend;
  38209. },
  38210. enumerable: true,
  38211. configurable: true
  38212. });
  38213. /**
  38214. * Gets the hosting scene
  38215. * @returns the hosting {BABYLON.Scene}
  38216. */
  38217. Geometry.prototype.getScene = function () {
  38218. return this._scene;
  38219. };
  38220. /**
  38221. * Gets the hosting engine
  38222. * @returns the hosting {BABYLON.Engine}
  38223. */
  38224. Geometry.prototype.getEngine = function () {
  38225. return this._engine;
  38226. };
  38227. /**
  38228. * Defines if the geometry is ready to use
  38229. * @returns true if the geometry is ready to be used
  38230. */
  38231. Geometry.prototype.isReady = function () {
  38232. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38233. };
  38234. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38235. /**
  38236. * Gets a value indicating that the geometry should not be serialized
  38237. */
  38238. get: function () {
  38239. for (var index = 0; index < this._meshes.length; index++) {
  38240. if (!this._meshes[index].doNotSerialize) {
  38241. return false;
  38242. }
  38243. }
  38244. return true;
  38245. },
  38246. enumerable: true,
  38247. configurable: true
  38248. });
  38249. /** @ignore */
  38250. Geometry.prototype._rebuild = function () {
  38251. if (this._vertexArrayObjects) {
  38252. this._vertexArrayObjects = {};
  38253. }
  38254. // Index buffer
  38255. if (this._meshes.length !== 0 && this._indices) {
  38256. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38257. }
  38258. // Vertex buffers
  38259. for (var key in this._vertexBuffers) {
  38260. var vertexBuffer = this._vertexBuffers[key];
  38261. vertexBuffer._rebuild();
  38262. }
  38263. };
  38264. /**
  38265. * Affects all gemetry data in one call
  38266. * @param vertexData defines the geometry data
  38267. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38268. */
  38269. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38270. vertexData.applyToGeometry(this, updatable);
  38271. this.notifyUpdate();
  38272. };
  38273. /**
  38274. * Set specific vertex data
  38275. * @param kind defines the data kind (Position, normal, etc...)
  38276. * @param data defines the vertex data to use
  38277. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38278. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38279. */
  38280. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38281. if (updatable === void 0) { updatable = false; }
  38282. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38283. this.setVerticesBuffer(buffer);
  38284. };
  38285. /**
  38286. * Removes a specific vertex data
  38287. * @param kind defines the data kind (Position, normal, etc...)
  38288. */
  38289. Geometry.prototype.removeVerticesData = function (kind) {
  38290. if (this._vertexBuffers[kind]) {
  38291. this._vertexBuffers[kind].dispose();
  38292. delete this._vertexBuffers[kind];
  38293. }
  38294. };
  38295. /**
  38296. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38297. * @param buffer defines the vertex buffer to use
  38298. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38299. */
  38300. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38301. if (totalVertices === void 0) { totalVertices = null; }
  38302. var kind = buffer.getKind();
  38303. if (this._vertexBuffers[kind]) {
  38304. this._vertexBuffers[kind].dispose();
  38305. }
  38306. this._vertexBuffers[kind] = buffer;
  38307. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38308. var data = buffer.getData();
  38309. if (totalVertices != null) {
  38310. this._totalVertices = totalVertices;
  38311. }
  38312. else {
  38313. if (data != null) {
  38314. this._totalVertices = data.length / (buffer.byteStride / 4);
  38315. }
  38316. }
  38317. this._updateExtend(data);
  38318. this._resetPointsArrayCache();
  38319. var meshes = this._meshes;
  38320. var numOfMeshes = meshes.length;
  38321. for (var index = 0; index < numOfMeshes; index++) {
  38322. var mesh = meshes[index];
  38323. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38324. mesh._createGlobalSubMesh(false);
  38325. mesh.computeWorldMatrix(true);
  38326. }
  38327. }
  38328. this.notifyUpdate(kind);
  38329. if (this._vertexArrayObjects) {
  38330. this._disposeVertexArrayObjects();
  38331. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38332. }
  38333. };
  38334. /**
  38335. * Update a specific vertex buffer
  38336. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38337. * It will do nothing if the buffer is not updatable
  38338. * @param kind defines the data kind (Position, normal, etc...)
  38339. * @param data defines the data to use
  38340. * @param offset defines the offset in the target buffer where to store the data
  38341. * @param useBytes set to true if the offset is in bytes
  38342. */
  38343. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38344. if (useBytes === void 0) { useBytes = false; }
  38345. var vertexBuffer = this.getVertexBuffer(kind);
  38346. if (!vertexBuffer) {
  38347. return;
  38348. }
  38349. vertexBuffer.updateDirectly(data, offset, useBytes);
  38350. this.notifyUpdate(kind);
  38351. };
  38352. /**
  38353. * Update a specific vertex buffer
  38354. * This function will create a new buffer if the current one is not updatable
  38355. * @param kind defines the data kind (Position, normal, etc...)
  38356. * @param data defines the data to use
  38357. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38358. */
  38359. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38360. if (updateExtends === void 0) { updateExtends = false; }
  38361. var vertexBuffer = this.getVertexBuffer(kind);
  38362. if (!vertexBuffer) {
  38363. return;
  38364. }
  38365. vertexBuffer.update(data);
  38366. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38367. this._updateBoundingInfo(updateExtends, data);
  38368. }
  38369. this.notifyUpdate(kind);
  38370. };
  38371. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38372. if (updateExtends) {
  38373. this._updateExtend(data);
  38374. }
  38375. var meshes = this._meshes;
  38376. var numOfMeshes = meshes.length;
  38377. this._resetPointsArrayCache();
  38378. for (var index = 0; index < numOfMeshes; index++) {
  38379. var mesh = meshes[index];
  38380. if (updateExtends) {
  38381. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38382. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38383. var subMesh = mesh.subMeshes[subIndex];
  38384. subMesh.refreshBoundingInfo();
  38385. }
  38386. }
  38387. }
  38388. };
  38389. /** @ignore */
  38390. Geometry.prototype._bind = function (effect, indexToBind) {
  38391. if (!effect) {
  38392. return;
  38393. }
  38394. if (indexToBind === undefined) {
  38395. indexToBind = this._indexBuffer;
  38396. }
  38397. var vbs = this.getVertexBuffers();
  38398. if (!vbs) {
  38399. return;
  38400. }
  38401. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38402. this._engine.bindBuffers(vbs, indexToBind, effect);
  38403. return;
  38404. }
  38405. // Using VAO
  38406. if (!this._vertexArrayObjects[effect.key]) {
  38407. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38408. }
  38409. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38410. };
  38411. /**
  38412. * Gets total number of vertices
  38413. * @returns the total number of vertices
  38414. */
  38415. Geometry.prototype.getTotalVertices = function () {
  38416. if (!this.isReady()) {
  38417. return 0;
  38418. }
  38419. return this._totalVertices;
  38420. };
  38421. /**
  38422. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38423. * @param kind defines the data kind (Position, normal, etc...)
  38424. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38425. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38426. * @returns a float array containing vertex data
  38427. */
  38428. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38429. var vertexBuffer = this.getVertexBuffer(kind);
  38430. if (!vertexBuffer) {
  38431. return null;
  38432. }
  38433. var data = vertexBuffer.getData();
  38434. if (!data) {
  38435. return null;
  38436. }
  38437. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38438. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38439. var count = this._totalVertices * defaultStride;
  38440. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38441. var copy_1 = new Array(count);
  38442. vertexBuffer.forEach(count, function (value, index) {
  38443. copy_1[index] = value;
  38444. });
  38445. return copy_1;
  38446. }
  38447. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38448. if (data instanceof Array) {
  38449. var offset = vertexBuffer.byteOffset / 4;
  38450. return BABYLON.Tools.Slice(data, offset, offset + count);
  38451. }
  38452. else if (data instanceof ArrayBuffer) {
  38453. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38454. }
  38455. else {
  38456. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38457. }
  38458. }
  38459. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38460. return BABYLON.Tools.Slice(data);
  38461. }
  38462. return data;
  38463. };
  38464. /**
  38465. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38466. * @param kind defines the data kind (Position, normal, etc...)
  38467. * @returns true if the vertex buffer with the specified kind is updatable
  38468. */
  38469. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38470. var vb = this._vertexBuffers[kind];
  38471. if (!vb) {
  38472. return false;
  38473. }
  38474. return vb.isUpdatable();
  38475. };
  38476. /**
  38477. * Gets a specific vertex buffer
  38478. * @param kind defines the data kind (Position, normal, etc...)
  38479. * @returns a {BABYLON.VertexBuffer}
  38480. */
  38481. Geometry.prototype.getVertexBuffer = function (kind) {
  38482. if (!this.isReady()) {
  38483. return null;
  38484. }
  38485. return this._vertexBuffers[kind];
  38486. };
  38487. /**
  38488. * Returns all vertex buffers
  38489. * @return an object holding all vertex buffers indexed by kind
  38490. */
  38491. Geometry.prototype.getVertexBuffers = function () {
  38492. if (!this.isReady()) {
  38493. return null;
  38494. }
  38495. return this._vertexBuffers;
  38496. };
  38497. /**
  38498. * Gets a boolean indicating if specific vertex buffer is present
  38499. * @param kind defines the data kind (Position, normal, etc...)
  38500. * @returns true if data is present
  38501. */
  38502. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38503. if (!this._vertexBuffers) {
  38504. if (this._delayInfo) {
  38505. return this._delayInfo.indexOf(kind) !== -1;
  38506. }
  38507. return false;
  38508. }
  38509. return this._vertexBuffers[kind] !== undefined;
  38510. };
  38511. /**
  38512. * Gets a list of all attached data kinds (Position, normal, etc...)
  38513. * @returns a list of string containing all kinds
  38514. */
  38515. Geometry.prototype.getVerticesDataKinds = function () {
  38516. var result = [];
  38517. var kind;
  38518. if (!this._vertexBuffers && this._delayInfo) {
  38519. for (kind in this._delayInfo) {
  38520. result.push(kind);
  38521. }
  38522. }
  38523. else {
  38524. for (kind in this._vertexBuffers) {
  38525. result.push(kind);
  38526. }
  38527. }
  38528. return result;
  38529. };
  38530. /**
  38531. * Update index buffer
  38532. * @param indices defines the indices to store in the index buffer
  38533. * @param offset defines the offset in the target buffer where to store the data
  38534. */
  38535. Geometry.prototype.updateIndices = function (indices, offset) {
  38536. if (!this._indexBuffer) {
  38537. return;
  38538. }
  38539. if (!this._indexBufferIsUpdatable) {
  38540. this.setIndices(indices, null, true);
  38541. }
  38542. else {
  38543. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38544. }
  38545. };
  38546. /**
  38547. * Creates a new index buffer
  38548. * @param indices defines the indices to store in the index buffer
  38549. * @param totalVertices defines the total number of vertices (could be null)
  38550. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38551. */
  38552. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38553. if (totalVertices === void 0) { totalVertices = null; }
  38554. if (updatable === void 0) { updatable = false; }
  38555. if (this._indexBuffer) {
  38556. this._engine._releaseBuffer(this._indexBuffer);
  38557. }
  38558. this._disposeVertexArrayObjects();
  38559. this._indices = indices;
  38560. this._indexBufferIsUpdatable = updatable;
  38561. if (this._meshes.length !== 0 && this._indices) {
  38562. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38563. }
  38564. if (totalVertices != undefined) { // including null and undefined
  38565. this._totalVertices = totalVertices;
  38566. }
  38567. var meshes = this._meshes;
  38568. var numOfMeshes = meshes.length;
  38569. for (var index = 0; index < numOfMeshes; index++) {
  38570. meshes[index]._createGlobalSubMesh(true);
  38571. }
  38572. this.notifyUpdate();
  38573. };
  38574. /**
  38575. * Return the total number of indices
  38576. * @returns the total number of indices
  38577. */
  38578. Geometry.prototype.getTotalIndices = function () {
  38579. if (!this.isReady()) {
  38580. return 0;
  38581. }
  38582. return this._indices.length;
  38583. };
  38584. /**
  38585. * Gets the index buffer array
  38586. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38587. * @returns the index buffer array
  38588. */
  38589. Geometry.prototype.getIndices = function (copyWhenShared) {
  38590. if (!this.isReady()) {
  38591. return null;
  38592. }
  38593. var orig = this._indices;
  38594. if (!copyWhenShared || this._meshes.length === 1) {
  38595. return orig;
  38596. }
  38597. else {
  38598. var len = orig.length;
  38599. var copy = [];
  38600. for (var i = 0; i < len; i++) {
  38601. copy.push(orig[i]);
  38602. }
  38603. return copy;
  38604. }
  38605. };
  38606. /**
  38607. * Gets the index buffer
  38608. * @return the index buffer
  38609. */
  38610. Geometry.prototype.getIndexBuffer = function () {
  38611. if (!this.isReady()) {
  38612. return null;
  38613. }
  38614. return this._indexBuffer;
  38615. };
  38616. /** @ignore */
  38617. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38618. if (effect === void 0) { effect = null; }
  38619. if (!effect || !this._vertexArrayObjects) {
  38620. return;
  38621. }
  38622. if (this._vertexArrayObjects[effect.key]) {
  38623. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38624. delete this._vertexArrayObjects[effect.key];
  38625. }
  38626. };
  38627. /**
  38628. * Release the associated resources for a specific mesh
  38629. * @param mesh defines the source mesh
  38630. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38631. */
  38632. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38633. var meshes = this._meshes;
  38634. var index = meshes.indexOf(mesh);
  38635. if (index === -1) {
  38636. return;
  38637. }
  38638. meshes.splice(index, 1);
  38639. mesh._geometry = null;
  38640. if (meshes.length === 0 && shouldDispose) {
  38641. this.dispose();
  38642. }
  38643. };
  38644. /**
  38645. * Apply current geometry to a given mesh
  38646. * @param mesh defines the mesh to apply geometry to
  38647. */
  38648. Geometry.prototype.applyToMesh = function (mesh) {
  38649. if (mesh._geometry === this) {
  38650. return;
  38651. }
  38652. var previousGeometry = mesh._geometry;
  38653. if (previousGeometry) {
  38654. previousGeometry.releaseForMesh(mesh);
  38655. }
  38656. var meshes = this._meshes;
  38657. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38658. mesh._geometry = this;
  38659. this._scene.pushGeometry(this);
  38660. meshes.push(mesh);
  38661. if (this.isReady()) {
  38662. this._applyToMesh(mesh);
  38663. }
  38664. else {
  38665. mesh._boundingInfo = this._boundingInfo;
  38666. }
  38667. };
  38668. Geometry.prototype._updateExtend = function (data) {
  38669. if (data === void 0) { data = null; }
  38670. if (!data) {
  38671. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38672. }
  38673. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38674. };
  38675. Geometry.prototype._applyToMesh = function (mesh) {
  38676. var numOfMeshes = this._meshes.length;
  38677. // vertexBuffers
  38678. for (var kind in this._vertexBuffers) {
  38679. if (numOfMeshes === 1) {
  38680. this._vertexBuffers[kind].create();
  38681. }
  38682. var buffer = this._vertexBuffers[kind].getBuffer();
  38683. if (buffer)
  38684. buffer.references = numOfMeshes;
  38685. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38686. if (!this._extend) {
  38687. this._updateExtend();
  38688. }
  38689. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38690. mesh._createGlobalSubMesh(false);
  38691. //bounding info was just created again, world matrix should be applied again.
  38692. mesh._updateBoundingInfo();
  38693. }
  38694. }
  38695. // indexBuffer
  38696. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38697. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38698. }
  38699. if (this._indexBuffer) {
  38700. this._indexBuffer.references = numOfMeshes;
  38701. }
  38702. };
  38703. Geometry.prototype.notifyUpdate = function (kind) {
  38704. if (this.onGeometryUpdated) {
  38705. this.onGeometryUpdated(this, kind);
  38706. }
  38707. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38708. var mesh = _a[_i];
  38709. mesh._markSubMeshesAsAttributesDirty();
  38710. }
  38711. };
  38712. /**
  38713. * Load the geometry if it was flagged as delay loaded
  38714. * @param scene defines the hosting scene
  38715. * @param onLoaded defines a callback called when the geometry is loaded
  38716. */
  38717. Geometry.prototype.load = function (scene, onLoaded) {
  38718. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38719. return;
  38720. }
  38721. if (this.isReady()) {
  38722. if (onLoaded) {
  38723. onLoaded();
  38724. }
  38725. return;
  38726. }
  38727. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38728. this._queueLoad(scene, onLoaded);
  38729. };
  38730. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38731. var _this = this;
  38732. if (!this.delayLoadingFile) {
  38733. return;
  38734. }
  38735. scene._addPendingData(this);
  38736. scene._loadFile(this.delayLoadingFile, function (data) {
  38737. if (!_this._delayLoadingFunction) {
  38738. return;
  38739. }
  38740. _this._delayLoadingFunction(JSON.parse(data), _this);
  38741. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38742. _this._delayInfo = [];
  38743. scene._removePendingData(_this);
  38744. var meshes = _this._meshes;
  38745. var numOfMeshes = meshes.length;
  38746. for (var index = 0; index < numOfMeshes; index++) {
  38747. _this._applyToMesh(meshes[index]);
  38748. }
  38749. if (onLoaded) {
  38750. onLoaded();
  38751. }
  38752. }, undefined, true);
  38753. };
  38754. /**
  38755. * Invert the geometry to move from a right handed system to a left handed one.
  38756. */
  38757. Geometry.prototype.toLeftHanded = function () {
  38758. // Flip faces
  38759. var tIndices = this.getIndices(false);
  38760. if (tIndices != null && tIndices.length > 0) {
  38761. for (var i = 0; i < tIndices.length; i += 3) {
  38762. var tTemp = tIndices[i + 0];
  38763. tIndices[i + 0] = tIndices[i + 2];
  38764. tIndices[i + 2] = tTemp;
  38765. }
  38766. this.setIndices(tIndices);
  38767. }
  38768. // Negate position.z
  38769. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38770. if (tPositions != null && tPositions.length > 0) {
  38771. for (var i = 0; i < tPositions.length; i += 3) {
  38772. tPositions[i + 2] = -tPositions[i + 2];
  38773. }
  38774. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38775. }
  38776. // Negate normal.z
  38777. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38778. if (tNormals != null && tNormals.length > 0) {
  38779. for (var i = 0; i < tNormals.length; i += 3) {
  38780. tNormals[i + 2] = -tNormals[i + 2];
  38781. }
  38782. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38783. }
  38784. };
  38785. // Cache
  38786. /** @ignore */
  38787. Geometry.prototype._resetPointsArrayCache = function () {
  38788. this._positions = null;
  38789. };
  38790. /** @ignore */
  38791. Geometry.prototype._generatePointsArray = function () {
  38792. if (this._positions)
  38793. return true;
  38794. this._positions = [];
  38795. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38796. if (!data) {
  38797. return false;
  38798. }
  38799. for (var index = 0; index < data.length; index += 3) {
  38800. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38801. }
  38802. return true;
  38803. };
  38804. /**
  38805. * Gets a value indicating if the geometry is disposed
  38806. * @returns true if the geometry was disposed
  38807. */
  38808. Geometry.prototype.isDisposed = function () {
  38809. return this._isDisposed;
  38810. };
  38811. Geometry.prototype._disposeVertexArrayObjects = function () {
  38812. if (this._vertexArrayObjects) {
  38813. for (var kind in this._vertexArrayObjects) {
  38814. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38815. }
  38816. this._vertexArrayObjects = {};
  38817. }
  38818. };
  38819. /**
  38820. * Free all associated resources
  38821. */
  38822. Geometry.prototype.dispose = function () {
  38823. var meshes = this._meshes;
  38824. var numOfMeshes = meshes.length;
  38825. var index;
  38826. for (index = 0; index < numOfMeshes; index++) {
  38827. this.releaseForMesh(meshes[index]);
  38828. }
  38829. this._meshes = [];
  38830. this._disposeVertexArrayObjects();
  38831. for (var kind in this._vertexBuffers) {
  38832. this._vertexBuffers[kind].dispose();
  38833. }
  38834. this._vertexBuffers = {};
  38835. this._totalVertices = 0;
  38836. if (this._indexBuffer) {
  38837. this._engine._releaseBuffer(this._indexBuffer);
  38838. }
  38839. this._indexBuffer = null;
  38840. this._indices = [];
  38841. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38842. this.delayLoadingFile = null;
  38843. this._delayLoadingFunction = null;
  38844. this._delayInfo = [];
  38845. this._boundingInfo = null;
  38846. this._scene.removeGeometry(this);
  38847. this._isDisposed = true;
  38848. };
  38849. /**
  38850. * Clone the current geometry into a new geometry
  38851. * @param id defines the unique ID of the new geometry
  38852. * @returns a new geometry object
  38853. */
  38854. Geometry.prototype.copy = function (id) {
  38855. var vertexData = new BABYLON.VertexData();
  38856. vertexData.indices = [];
  38857. var indices = this.getIndices();
  38858. if (indices) {
  38859. for (var index = 0; index < indices.length; index++) {
  38860. vertexData.indices.push(indices[index]);
  38861. }
  38862. }
  38863. var updatable = false;
  38864. var stopChecking = false;
  38865. var kind;
  38866. for (kind in this._vertexBuffers) {
  38867. // using slice() to make a copy of the array and not just reference it
  38868. var data = this.getVerticesData(kind);
  38869. if (data instanceof Float32Array) {
  38870. vertexData.set(new Float32Array(data), kind);
  38871. }
  38872. else {
  38873. vertexData.set(data.slice(0), kind);
  38874. }
  38875. if (!stopChecking) {
  38876. var vb = this.getVertexBuffer(kind);
  38877. if (vb) {
  38878. updatable = vb.isUpdatable();
  38879. stopChecking = !updatable;
  38880. }
  38881. }
  38882. }
  38883. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38884. geometry.delayLoadState = this.delayLoadState;
  38885. geometry.delayLoadingFile = this.delayLoadingFile;
  38886. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38887. for (kind in this._delayInfo) {
  38888. geometry._delayInfo = geometry._delayInfo || [];
  38889. geometry._delayInfo.push(kind);
  38890. }
  38891. // Bounding info
  38892. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38893. return geometry;
  38894. };
  38895. /**
  38896. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38897. * @return a JSON representation of the current geometry data (without the vertices data)
  38898. */
  38899. Geometry.prototype.serialize = function () {
  38900. var serializationObject = {};
  38901. serializationObject.id = this.id;
  38902. serializationObject.updatable = this._updatable;
  38903. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38904. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38905. }
  38906. return serializationObject;
  38907. };
  38908. Geometry.prototype.toNumberArray = function (origin) {
  38909. if (Array.isArray(origin)) {
  38910. return origin;
  38911. }
  38912. else {
  38913. return Array.prototype.slice.call(origin);
  38914. }
  38915. };
  38916. /**
  38917. * Serialize all vertices data into a JSON oject
  38918. * @returns a JSON representation of the current geometry data
  38919. */
  38920. Geometry.prototype.serializeVerticeData = function () {
  38921. var serializationObject = this.serialize();
  38922. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38923. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38924. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38925. serializationObject.positions._updatable = true;
  38926. }
  38927. }
  38928. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38929. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38930. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38931. serializationObject.normals._updatable = true;
  38932. }
  38933. }
  38934. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38935. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38936. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38937. serializationObject.tangets._updatable = true;
  38938. }
  38939. }
  38940. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38941. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38942. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38943. serializationObject.uvs._updatable = true;
  38944. }
  38945. }
  38946. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38947. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  38948. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  38949. serializationObject.uv2s._updatable = true;
  38950. }
  38951. }
  38952. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38953. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  38954. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  38955. serializationObject.uv3s._updatable = true;
  38956. }
  38957. }
  38958. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38959. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  38960. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  38961. serializationObject.uv4s._updatable = true;
  38962. }
  38963. }
  38964. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38965. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  38966. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  38967. serializationObject.uv5s._updatable = true;
  38968. }
  38969. }
  38970. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38971. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  38972. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  38973. serializationObject.uv6s._updatable = true;
  38974. }
  38975. }
  38976. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38977. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  38978. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  38979. serializationObject.colors._updatable = true;
  38980. }
  38981. }
  38982. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38983. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  38984. serializationObject.matricesIndices._isExpanded = true;
  38985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38986. serializationObject.matricesIndices._updatable = true;
  38987. }
  38988. }
  38989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38990. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  38991. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38992. serializationObject.matricesWeights._updatable = true;
  38993. }
  38994. }
  38995. serializationObject.indices = this.toNumberArray(this.getIndices());
  38996. return serializationObject;
  38997. };
  38998. // Statics
  38999. /**
  39000. * Extracts a clone of a mesh geometry
  39001. * @param mesh defines the source mesh
  39002. * @param id defines the unique ID of the new geometry object
  39003. * @returns the new geometry object
  39004. */
  39005. Geometry.ExtractFromMesh = function (mesh, id) {
  39006. var geometry = mesh._geometry;
  39007. if (!geometry) {
  39008. return null;
  39009. }
  39010. return geometry.copy(id);
  39011. };
  39012. /**
  39013. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39014. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39015. * Be aware Math.random() could cause collisions, but:
  39016. * "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"
  39017. * @returns a string containing a new GUID
  39018. */
  39019. Geometry.RandomId = function () {
  39020. return BABYLON.Tools.RandomId();
  39021. };
  39022. /** @ignore */
  39023. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39024. var scene = mesh.getScene();
  39025. // Geometry
  39026. var geometryId = parsedGeometry.geometryId;
  39027. if (geometryId) {
  39028. var geometry = scene.getGeometryByID(geometryId);
  39029. if (geometry) {
  39030. geometry.applyToMesh(mesh);
  39031. }
  39032. }
  39033. else if (parsedGeometry instanceof ArrayBuffer) {
  39034. var binaryInfo = mesh._binaryInfo;
  39035. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39036. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39037. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39038. }
  39039. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39040. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39041. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39042. }
  39043. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39044. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39045. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39046. }
  39047. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39048. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39049. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39050. }
  39051. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39052. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39053. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39054. }
  39055. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39056. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39057. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39058. }
  39059. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39060. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39061. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39062. }
  39063. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39064. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39065. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39066. }
  39067. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39068. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39069. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39070. }
  39071. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39072. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39073. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39074. }
  39075. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39076. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39077. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39078. }
  39079. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39080. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39081. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39082. }
  39083. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39084. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39085. mesh.setIndices(indicesData, null);
  39086. }
  39087. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39088. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39089. mesh.subMeshes = [];
  39090. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39091. var materialIndex = subMeshesData[(i * 5) + 0];
  39092. var verticesStart = subMeshesData[(i * 5) + 1];
  39093. var verticesCount = subMeshesData[(i * 5) + 2];
  39094. var indexStart = subMeshesData[(i * 5) + 3];
  39095. var indexCount = subMeshesData[(i * 5) + 4];
  39096. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39097. }
  39098. }
  39099. }
  39100. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39101. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39102. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39103. if (parsedGeometry.tangents) {
  39104. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39105. }
  39106. if (parsedGeometry.uvs) {
  39107. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39108. }
  39109. if (parsedGeometry.uvs2) {
  39110. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39111. }
  39112. if (parsedGeometry.uvs3) {
  39113. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39114. }
  39115. if (parsedGeometry.uvs4) {
  39116. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39117. }
  39118. if (parsedGeometry.uvs5) {
  39119. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39120. }
  39121. if (parsedGeometry.uvs6) {
  39122. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39123. }
  39124. if (parsedGeometry.colors) {
  39125. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39126. }
  39127. if (parsedGeometry.matricesIndices) {
  39128. if (!parsedGeometry.matricesIndices._isExpanded) {
  39129. var floatIndices = [];
  39130. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39131. var matricesIndex = parsedGeometry.matricesIndices[i];
  39132. floatIndices.push(matricesIndex & 0x000000FF);
  39133. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39134. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39135. floatIndices.push(matricesIndex >> 24);
  39136. }
  39137. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39138. }
  39139. else {
  39140. delete parsedGeometry.matricesIndices._isExpanded;
  39141. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39142. }
  39143. }
  39144. if (parsedGeometry.matricesIndicesExtra) {
  39145. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39146. var floatIndices = [];
  39147. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39148. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39149. floatIndices.push(matricesIndex & 0x000000FF);
  39150. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39151. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39152. floatIndices.push(matricesIndex >> 24);
  39153. }
  39154. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39155. }
  39156. else {
  39157. delete parsedGeometry.matricesIndices._isExpanded;
  39158. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39159. }
  39160. }
  39161. if (parsedGeometry.matricesWeights) {
  39162. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39163. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39164. }
  39165. if (parsedGeometry.matricesWeightsExtra) {
  39166. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39167. }
  39168. mesh.setIndices(parsedGeometry.indices, null);
  39169. }
  39170. // SubMeshes
  39171. if (parsedGeometry.subMeshes) {
  39172. mesh.subMeshes = [];
  39173. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39174. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39175. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39176. }
  39177. }
  39178. // Flat shading
  39179. if (mesh._shouldGenerateFlatShading) {
  39180. mesh.convertToFlatShadedMesh();
  39181. delete mesh._shouldGenerateFlatShading;
  39182. }
  39183. // Update
  39184. mesh.computeWorldMatrix(true);
  39185. // Octree
  39186. var sceneOctree = scene.selectionOctree;
  39187. if (sceneOctree !== undefined && sceneOctree !== null) {
  39188. sceneOctree.addMesh(mesh);
  39189. }
  39190. };
  39191. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39192. var epsilon = 1e-3;
  39193. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39194. return;
  39195. }
  39196. var noInfluenceBoneIndex = 0.0;
  39197. if (parsedGeometry.skeletonId > -1) {
  39198. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39199. if (!skeleton) {
  39200. return;
  39201. }
  39202. noInfluenceBoneIndex = skeleton.bones.length;
  39203. }
  39204. else {
  39205. return;
  39206. }
  39207. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39208. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39209. var matricesWeights = parsedGeometry.matricesWeights;
  39210. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39211. var influencers = parsedGeometry.numBoneInfluencer;
  39212. var size = matricesWeights.length;
  39213. for (var i = 0; i < size; i += 4) {
  39214. var weight = 0.0;
  39215. var firstZeroWeight = -1;
  39216. for (var j = 0; j < 4; j++) {
  39217. var w = matricesWeights[i + j];
  39218. weight += w;
  39219. if (w < epsilon && firstZeroWeight < 0) {
  39220. firstZeroWeight = j;
  39221. }
  39222. }
  39223. if (matricesWeightsExtra) {
  39224. for (var j = 0; j < 4; j++) {
  39225. var w = matricesWeightsExtra[i + j];
  39226. weight += w;
  39227. if (w < epsilon && firstZeroWeight < 0) {
  39228. firstZeroWeight = j + 4;
  39229. }
  39230. }
  39231. }
  39232. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39233. firstZeroWeight = influencers - 1;
  39234. }
  39235. if (weight > epsilon) {
  39236. var mweight = 1.0 / weight;
  39237. for (var j = 0; j < 4; j++) {
  39238. matricesWeights[i + j] *= mweight;
  39239. }
  39240. if (matricesWeightsExtra) {
  39241. for (var j = 0; j < 4; j++) {
  39242. matricesWeightsExtra[i + j] *= mweight;
  39243. }
  39244. }
  39245. }
  39246. else {
  39247. if (firstZeroWeight >= 4) {
  39248. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39249. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39250. }
  39251. else {
  39252. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39253. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39254. }
  39255. }
  39256. }
  39257. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39258. if (parsedGeometry.matricesWeightsExtra) {
  39259. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39260. }
  39261. };
  39262. /**
  39263. * Create a new geometry from persisted data (Using .babylon file format)
  39264. * @param parsedVertexData defines the persisted data
  39265. * @param scene defines the hosting scene
  39266. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39267. * @returns the new geometry object
  39268. */
  39269. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39270. if (scene.getGeometryByID(parsedVertexData.id)) {
  39271. return null; // null since geometry could be something else than a box...
  39272. }
  39273. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39274. if (BABYLON.Tags) {
  39275. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39276. }
  39277. if (parsedVertexData.delayLoadingFile) {
  39278. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39279. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39280. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39281. geometry._delayInfo = [];
  39282. if (parsedVertexData.hasUVs) {
  39283. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39284. }
  39285. if (parsedVertexData.hasUVs2) {
  39286. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39287. }
  39288. if (parsedVertexData.hasUVs3) {
  39289. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39290. }
  39291. if (parsedVertexData.hasUVs4) {
  39292. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39293. }
  39294. if (parsedVertexData.hasUVs5) {
  39295. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39296. }
  39297. if (parsedVertexData.hasUVs6) {
  39298. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39299. }
  39300. if (parsedVertexData.hasColors) {
  39301. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39302. }
  39303. if (parsedVertexData.hasMatricesIndices) {
  39304. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39305. }
  39306. if (parsedVertexData.hasMatricesWeights) {
  39307. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39308. }
  39309. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39310. }
  39311. else {
  39312. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39313. }
  39314. scene.pushGeometry(geometry, true);
  39315. return geometry;
  39316. };
  39317. return Geometry;
  39318. }());
  39319. BABYLON.Geometry = Geometry;
  39320. // Primitives
  39321. /// Abstract class
  39322. /**
  39323. * Abstract class used to provide common services for all typed geometries
  39324. */
  39325. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39326. __extends(_PrimitiveGeometry, _super);
  39327. /**
  39328. * Creates a new typed geometry
  39329. * @param id defines the unique ID of the geometry
  39330. * @param scene defines the hosting scene
  39331. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39332. * @param mesh defines the hosting mesh (can be null)
  39333. */
  39334. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39335. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39336. if (mesh === void 0) { mesh = null; }
  39337. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39338. _this._canBeRegenerated = _canBeRegenerated;
  39339. _this._beingRegenerated = true;
  39340. _this.regenerate();
  39341. _this._beingRegenerated = false;
  39342. return _this;
  39343. }
  39344. /**
  39345. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39346. * @returns true if the geometry can be regenerated
  39347. */
  39348. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39349. return this._canBeRegenerated;
  39350. };
  39351. /**
  39352. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39353. */
  39354. _PrimitiveGeometry.prototype.regenerate = function () {
  39355. if (!this._canBeRegenerated) {
  39356. return;
  39357. }
  39358. this._beingRegenerated = true;
  39359. this.setAllVerticesData(this._regenerateVertexData(), false);
  39360. this._beingRegenerated = false;
  39361. };
  39362. /**
  39363. * Clone the geometry
  39364. * @param id defines the unique ID of the new geometry
  39365. * @returns the new geometry
  39366. */
  39367. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39368. return _super.prototype.copy.call(this, id);
  39369. };
  39370. // overrides
  39371. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39372. if (!this._beingRegenerated) {
  39373. return;
  39374. }
  39375. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39376. };
  39377. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39378. if (!this._beingRegenerated) {
  39379. return;
  39380. }
  39381. _super.prototype.setVerticesData.call(this, kind, data, false);
  39382. };
  39383. // to override
  39384. /** @ignore */
  39385. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39386. throw new Error("Abstract method");
  39387. };
  39388. _PrimitiveGeometry.prototype.copy = function (id) {
  39389. throw new Error("Must be overriden in sub-classes.");
  39390. };
  39391. _PrimitiveGeometry.prototype.serialize = function () {
  39392. var serializationObject = _super.prototype.serialize.call(this);
  39393. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39394. return serializationObject;
  39395. };
  39396. return _PrimitiveGeometry;
  39397. }(Geometry));
  39398. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39399. /**
  39400. * Creates a ribbon geometry
  39401. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39402. */
  39403. var RibbonGeometry = /** @class */ (function (_super) {
  39404. __extends(RibbonGeometry, _super);
  39405. /**
  39406. * Creates a ribbon geometry
  39407. * @param id defines the unique ID of the geometry
  39408. * @param scene defines the hosting scene
  39409. * @param pathArray defines the array of paths to use
  39410. * @param closeArray defines if the last path and the first path must be joined
  39411. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39412. * @param offset defines the offset between points
  39413. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39414. * @param mesh defines the hosting mesh (can be null)
  39415. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39416. */
  39417. function RibbonGeometry(id, scene,
  39418. /**
  39419. * Defines the array of paths to use
  39420. */
  39421. pathArray,
  39422. /**
  39423. * Defines if the last and first points of each path in your pathArray must be joined
  39424. */
  39425. closeArray,
  39426. /**
  39427. * Defines if the last and first points of each path in your pathArray must be joined
  39428. */
  39429. closePath,
  39430. /**
  39431. * Defines the offset between points
  39432. */
  39433. offset, canBeRegenerated, mesh,
  39434. /**
  39435. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39436. */
  39437. side) {
  39438. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39439. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39440. _this.pathArray = pathArray;
  39441. _this.closeArray = closeArray;
  39442. _this.closePath = closePath;
  39443. _this.offset = offset;
  39444. _this.side = side;
  39445. return _this;
  39446. }
  39447. /** @ignore */
  39448. RibbonGeometry.prototype._regenerateVertexData = function () {
  39449. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39450. };
  39451. RibbonGeometry.prototype.copy = function (id) {
  39452. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39453. };
  39454. return RibbonGeometry;
  39455. }(_PrimitiveGeometry));
  39456. BABYLON.RibbonGeometry = RibbonGeometry;
  39457. /**
  39458. * Creates a box geometry
  39459. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39460. */
  39461. var BoxGeometry = /** @class */ (function (_super) {
  39462. __extends(BoxGeometry, _super);
  39463. /**
  39464. * Creates a box geometry
  39465. * @param id defines the unique ID of the geometry
  39466. * @param scene defines the hosting scene
  39467. * @param size defines the zise of the box (width, height and depth are the same)
  39468. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39469. * @param mesh defines the hosting mesh (can be null)
  39470. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39471. */
  39472. function BoxGeometry(id, scene,
  39473. /**
  39474. * Defines the zise of the box (width, height and depth are the same)
  39475. */
  39476. size, canBeRegenerated, mesh,
  39477. /**
  39478. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39479. */
  39480. side) {
  39481. if (mesh === void 0) { mesh = null; }
  39482. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39483. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39484. _this.size = size;
  39485. _this.side = side;
  39486. return _this;
  39487. }
  39488. BoxGeometry.prototype._regenerateVertexData = function () {
  39489. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39490. };
  39491. BoxGeometry.prototype.copy = function (id) {
  39492. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39493. };
  39494. BoxGeometry.prototype.serialize = function () {
  39495. var serializationObject = _super.prototype.serialize.call(this);
  39496. serializationObject.size = this.size;
  39497. return serializationObject;
  39498. };
  39499. BoxGeometry.Parse = function (parsedBox, scene) {
  39500. if (scene.getGeometryByID(parsedBox.id)) {
  39501. return null; // null since geometry could be something else than a box...
  39502. }
  39503. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39504. if (BABYLON.Tags) {
  39505. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39506. }
  39507. scene.pushGeometry(box, true);
  39508. return box;
  39509. };
  39510. return BoxGeometry;
  39511. }(_PrimitiveGeometry));
  39512. BABYLON.BoxGeometry = BoxGeometry;
  39513. /**
  39514. * Creates a sphere geometry
  39515. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39516. */
  39517. var SphereGeometry = /** @class */ (function (_super) {
  39518. __extends(SphereGeometry, _super);
  39519. /**
  39520. * Create a new sphere geometry
  39521. * @param id defines the unique ID of the geometry
  39522. * @param scene defines the hosting scene
  39523. * @param segments defines the number of segments to use to create the sphere
  39524. * @param diameter defines the diameter of the sphere
  39525. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39526. * @param mesh defines the hosting mesh (can be null)
  39527. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39528. */
  39529. function SphereGeometry(id, scene,
  39530. /**
  39531. * Defines the number of segments to use to create the sphere
  39532. */
  39533. segments,
  39534. /**
  39535. * Defines the diameter of the sphere
  39536. */
  39537. diameter, canBeRegenerated, mesh,
  39538. /**
  39539. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39540. */
  39541. side) {
  39542. if (mesh === void 0) { mesh = null; }
  39543. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39544. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39545. _this.segments = segments;
  39546. _this.diameter = diameter;
  39547. _this.side = side;
  39548. return _this;
  39549. }
  39550. SphereGeometry.prototype._regenerateVertexData = function () {
  39551. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39552. };
  39553. SphereGeometry.prototype.copy = function (id) {
  39554. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39555. };
  39556. SphereGeometry.prototype.serialize = function () {
  39557. var serializationObject = _super.prototype.serialize.call(this);
  39558. serializationObject.segments = this.segments;
  39559. serializationObject.diameter = this.diameter;
  39560. return serializationObject;
  39561. };
  39562. SphereGeometry.Parse = function (parsedSphere, scene) {
  39563. if (scene.getGeometryByID(parsedSphere.id)) {
  39564. return null; // null since geometry could be something else than a sphere...
  39565. }
  39566. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39567. if (BABYLON.Tags) {
  39568. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39569. }
  39570. scene.pushGeometry(sphere, true);
  39571. return sphere;
  39572. };
  39573. return SphereGeometry;
  39574. }(_PrimitiveGeometry));
  39575. BABYLON.SphereGeometry = SphereGeometry;
  39576. /**
  39577. * Creates a disc geometry
  39578. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39579. */
  39580. var DiscGeometry = /** @class */ (function (_super) {
  39581. __extends(DiscGeometry, _super);
  39582. /**
  39583. * Creates a new disc geometry
  39584. * @param id defines the unique ID of the geometry
  39585. * @param scene defines the hosting scene
  39586. * @param radius defines the radius of the disc
  39587. * @param tessellation defines the tesselation factor to apply to the disc
  39588. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39589. * @param mesh defines the hosting mesh (can be null)
  39590. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39591. */
  39592. function DiscGeometry(id, scene,
  39593. /**
  39594. * Defines the radius of the disc
  39595. */
  39596. radius,
  39597. /**
  39598. * Defines the tesselation factor to apply to the disc
  39599. */
  39600. tessellation, canBeRegenerated, mesh,
  39601. /**
  39602. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39603. */
  39604. side) {
  39605. if (mesh === void 0) { mesh = null; }
  39606. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39607. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39608. _this.radius = radius;
  39609. _this.tessellation = tessellation;
  39610. _this.side = side;
  39611. return _this;
  39612. }
  39613. DiscGeometry.prototype._regenerateVertexData = function () {
  39614. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39615. };
  39616. DiscGeometry.prototype.copy = function (id) {
  39617. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39618. };
  39619. return DiscGeometry;
  39620. }(_PrimitiveGeometry));
  39621. BABYLON.DiscGeometry = DiscGeometry;
  39622. /**
  39623. * Creates a new cylinder geometry
  39624. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39625. */
  39626. var CylinderGeometry = /** @class */ (function (_super) {
  39627. __extends(CylinderGeometry, _super);
  39628. /**
  39629. * Creates a new cylinder geometry
  39630. * @param id defines the unique ID of the geometry
  39631. * @param scene defines the hosting scene
  39632. * @param height defines the height of the cylinder
  39633. * @param diameterTop defines the diameter of the cylinder's top cap
  39634. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39635. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39636. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39637. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39638. * @param mesh defines the hosting mesh (can be null)
  39639. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39640. */
  39641. function CylinderGeometry(id, scene,
  39642. /**
  39643. * Defines the height of the cylinder
  39644. */
  39645. height,
  39646. /**
  39647. * Defines the diameter of the cylinder's top cap
  39648. */
  39649. diameterTop,
  39650. /**
  39651. * Defines the diameter of the cylinder's bottom cap
  39652. */
  39653. diameterBottom,
  39654. /**
  39655. * Defines the tessellation factor to apply to the cylinder
  39656. */
  39657. tessellation,
  39658. /**
  39659. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39660. */
  39661. subdivisions, canBeRegenerated, mesh,
  39662. /**
  39663. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39664. */
  39665. side) {
  39666. if (subdivisions === void 0) { subdivisions = 1; }
  39667. if (mesh === void 0) { mesh = null; }
  39668. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39669. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39670. _this.height = height;
  39671. _this.diameterTop = diameterTop;
  39672. _this.diameterBottom = diameterBottom;
  39673. _this.tessellation = tessellation;
  39674. _this.subdivisions = subdivisions;
  39675. _this.side = side;
  39676. return _this;
  39677. }
  39678. CylinderGeometry.prototype._regenerateVertexData = function () {
  39679. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39680. };
  39681. CylinderGeometry.prototype.copy = function (id) {
  39682. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39683. };
  39684. CylinderGeometry.prototype.serialize = function () {
  39685. var serializationObject = _super.prototype.serialize.call(this);
  39686. serializationObject.height = this.height;
  39687. serializationObject.diameterTop = this.diameterTop;
  39688. serializationObject.diameterBottom = this.diameterBottom;
  39689. serializationObject.tessellation = this.tessellation;
  39690. return serializationObject;
  39691. };
  39692. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39693. if (scene.getGeometryByID(parsedCylinder.id)) {
  39694. return null; // null since geometry could be something else than a cylinder...
  39695. }
  39696. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39697. if (BABYLON.Tags) {
  39698. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39699. }
  39700. scene.pushGeometry(cylinder, true);
  39701. return cylinder;
  39702. };
  39703. return CylinderGeometry;
  39704. }(_PrimitiveGeometry));
  39705. BABYLON.CylinderGeometry = CylinderGeometry;
  39706. /**
  39707. * Creates a new torus geometry
  39708. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39709. */
  39710. var TorusGeometry = /** @class */ (function (_super) {
  39711. __extends(TorusGeometry, _super);
  39712. /**
  39713. * Creates a new torus geometry
  39714. * @param id defines the unique ID of the geometry
  39715. * @param scene defines the hosting scene
  39716. * @param diameter defines the diameter of the torus
  39717. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39718. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39719. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39720. * @param mesh defines the hosting mesh (can be null)
  39721. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39722. */
  39723. function TorusGeometry(id, scene,
  39724. /**
  39725. * Defines the diameter of the torus
  39726. */
  39727. diameter,
  39728. /**
  39729. * Defines the thickness of the torus (ie. internal diameter)
  39730. */
  39731. thickness,
  39732. /**
  39733. * Defines the tesselation factor to apply to the torus
  39734. */
  39735. tessellation, canBeRegenerated, mesh,
  39736. /**
  39737. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39738. */
  39739. side) {
  39740. if (mesh === void 0) { mesh = null; }
  39741. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39742. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39743. _this.diameter = diameter;
  39744. _this.thickness = thickness;
  39745. _this.tessellation = tessellation;
  39746. _this.side = side;
  39747. return _this;
  39748. }
  39749. TorusGeometry.prototype._regenerateVertexData = function () {
  39750. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39751. };
  39752. TorusGeometry.prototype.copy = function (id) {
  39753. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39754. };
  39755. TorusGeometry.prototype.serialize = function () {
  39756. var serializationObject = _super.prototype.serialize.call(this);
  39757. serializationObject.diameter = this.diameter;
  39758. serializationObject.thickness = this.thickness;
  39759. serializationObject.tessellation = this.tessellation;
  39760. return serializationObject;
  39761. };
  39762. TorusGeometry.Parse = function (parsedTorus, scene) {
  39763. if (scene.getGeometryByID(parsedTorus.id)) {
  39764. return null; // null since geometry could be something else than a torus...
  39765. }
  39766. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39767. if (BABYLON.Tags) {
  39768. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39769. }
  39770. scene.pushGeometry(torus, true);
  39771. return torus;
  39772. };
  39773. return TorusGeometry;
  39774. }(_PrimitiveGeometry));
  39775. BABYLON.TorusGeometry = TorusGeometry;
  39776. /**
  39777. * Creates a new ground geometry
  39778. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39779. */
  39780. var GroundGeometry = /** @class */ (function (_super) {
  39781. __extends(GroundGeometry, _super);
  39782. /**
  39783. * Creates a new ground geometry
  39784. * @param id defines the unique ID of the geometry
  39785. * @param scene defines the hosting scene
  39786. * @param width defines the width of the ground
  39787. * @param height defines the height of the ground
  39788. * @param subdivisions defines the subdivisions to apply to the ground
  39789. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39790. * @param mesh defines the hosting mesh (can be null)
  39791. */
  39792. function GroundGeometry(id, scene,
  39793. /**
  39794. * Defines the width of the ground
  39795. */
  39796. width,
  39797. /**
  39798. * Defines the height of the ground
  39799. */
  39800. height,
  39801. /**
  39802. * Defines the subdivisions to apply to the ground
  39803. */
  39804. subdivisions, canBeRegenerated, mesh) {
  39805. if (mesh === void 0) { mesh = null; }
  39806. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39807. _this.width = width;
  39808. _this.height = height;
  39809. _this.subdivisions = subdivisions;
  39810. return _this;
  39811. }
  39812. GroundGeometry.prototype._regenerateVertexData = function () {
  39813. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39814. };
  39815. GroundGeometry.prototype.copy = function (id) {
  39816. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39817. };
  39818. GroundGeometry.prototype.serialize = function () {
  39819. var serializationObject = _super.prototype.serialize.call(this);
  39820. serializationObject.width = this.width;
  39821. serializationObject.height = this.height;
  39822. serializationObject.subdivisions = this.subdivisions;
  39823. return serializationObject;
  39824. };
  39825. GroundGeometry.Parse = function (parsedGround, scene) {
  39826. if (scene.getGeometryByID(parsedGround.id)) {
  39827. return null; // null since geometry could be something else than a ground...
  39828. }
  39829. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39830. if (BABYLON.Tags) {
  39831. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39832. }
  39833. scene.pushGeometry(ground, true);
  39834. return ground;
  39835. };
  39836. return GroundGeometry;
  39837. }(_PrimitiveGeometry));
  39838. BABYLON.GroundGeometry = GroundGeometry;
  39839. /**
  39840. * Creates a tiled ground geometry
  39841. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39842. */
  39843. var TiledGroundGeometry = /** @class */ (function (_super) {
  39844. __extends(TiledGroundGeometry, _super);
  39845. /**
  39846. * Creates a tiled ground geometry
  39847. * @param id defines the unique ID of the geometry
  39848. * @param scene defines the hosting scene
  39849. * @param xmin defines the minimum value on X axis
  39850. * @param zmin defines the minimum value on Z axis
  39851. * @param xmax defines the maximum value on X axis
  39852. * @param zmax defines the maximum value on Z axis
  39853. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39854. * @param precision defines the precision to use when computing the tiles
  39855. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39856. * @param mesh defines the hosting mesh (can be null)
  39857. */
  39858. function TiledGroundGeometry(id, scene,
  39859. /**
  39860. * Defines the minimum value on X axis
  39861. */
  39862. xmin,
  39863. /**
  39864. * Defines the minimum value on Z axis
  39865. */
  39866. zmin,
  39867. /**
  39868. * Defines the maximum value on X axis
  39869. */
  39870. xmax,
  39871. /**
  39872. * Defines the maximum value on Z axis
  39873. */
  39874. zmax,
  39875. /**
  39876. * Defines the subdivisions to apply to the ground
  39877. */
  39878. subdivisions,
  39879. /**
  39880. * Defines the precision to use when computing the tiles
  39881. */
  39882. precision, canBeRegenerated, mesh) {
  39883. if (mesh === void 0) { mesh = null; }
  39884. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39885. _this.xmin = xmin;
  39886. _this.zmin = zmin;
  39887. _this.xmax = xmax;
  39888. _this.zmax = zmax;
  39889. _this.subdivisions = subdivisions;
  39890. _this.precision = precision;
  39891. return _this;
  39892. }
  39893. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39894. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39895. };
  39896. TiledGroundGeometry.prototype.copy = function (id) {
  39897. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39898. };
  39899. return TiledGroundGeometry;
  39900. }(_PrimitiveGeometry));
  39901. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39902. /**
  39903. * Creates a plane geometry
  39904. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39905. */
  39906. var PlaneGeometry = /** @class */ (function (_super) {
  39907. __extends(PlaneGeometry, _super);
  39908. /**
  39909. * Creates a plane geometry
  39910. * @param id defines the unique ID of the geometry
  39911. * @param scene defines the hosting scene
  39912. * @param size defines the size of the plane (width === height)
  39913. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39914. * @param mesh defines the hosting mesh (can be null)
  39915. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39916. */
  39917. function PlaneGeometry(id, scene,
  39918. /**
  39919. * Defines the size of the plane (width === height)
  39920. */
  39921. size, canBeRegenerated, mesh,
  39922. /**
  39923. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39924. */
  39925. side) {
  39926. if (mesh === void 0) { mesh = null; }
  39927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39928. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39929. _this.size = size;
  39930. _this.side = side;
  39931. return _this;
  39932. }
  39933. PlaneGeometry.prototype._regenerateVertexData = function () {
  39934. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39935. };
  39936. PlaneGeometry.prototype.copy = function (id) {
  39937. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39938. };
  39939. PlaneGeometry.prototype.serialize = function () {
  39940. var serializationObject = _super.prototype.serialize.call(this);
  39941. serializationObject.size = this.size;
  39942. return serializationObject;
  39943. };
  39944. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39945. if (scene.getGeometryByID(parsedPlane.id)) {
  39946. return null; // null since geometry could be something else than a ground...
  39947. }
  39948. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  39949. if (BABYLON.Tags) {
  39950. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  39951. }
  39952. scene.pushGeometry(plane, true);
  39953. return plane;
  39954. };
  39955. return PlaneGeometry;
  39956. }(_PrimitiveGeometry));
  39957. BABYLON.PlaneGeometry = PlaneGeometry;
  39958. /**
  39959. * Creates a torus knot geometry
  39960. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  39961. */
  39962. var TorusKnotGeometry = /** @class */ (function (_super) {
  39963. __extends(TorusKnotGeometry, _super);
  39964. /**
  39965. * Creates a torus knot geometry
  39966. * @param id defines the unique ID of the geometry
  39967. * @param scene defines the hosting scene
  39968. * @param radius defines the radius of the torus knot
  39969. * @param tube defines the thickness of the torus knot tube
  39970. * @param radialSegments defines the number of radial segments
  39971. * @param tubularSegments defines the number of tubular segments
  39972. * @param p defines the first number of windings
  39973. * @param q defines the second number of windings
  39974. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39975. * @param mesh defines the hosting mesh (can be null)
  39976. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39977. */
  39978. function TorusKnotGeometry(id, scene,
  39979. /**
  39980. * Defines the radius of the torus knot
  39981. */
  39982. radius,
  39983. /**
  39984. * Defines the thickness of the torus knot tube
  39985. */
  39986. tube,
  39987. /**
  39988. * Defines the number of radial segments
  39989. */
  39990. radialSegments,
  39991. /**
  39992. * Defines the number of tubular segments
  39993. */
  39994. tubularSegments,
  39995. /**
  39996. * Defines the first number of windings
  39997. */
  39998. p,
  39999. /**
  40000. * Defines the second number of windings
  40001. */
  40002. q, canBeRegenerated, mesh,
  40003. /**
  40004. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40005. */
  40006. side) {
  40007. if (mesh === void 0) { mesh = null; }
  40008. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40009. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40010. _this.radius = radius;
  40011. _this.tube = tube;
  40012. _this.radialSegments = radialSegments;
  40013. _this.tubularSegments = tubularSegments;
  40014. _this.p = p;
  40015. _this.q = q;
  40016. _this.side = side;
  40017. return _this;
  40018. }
  40019. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40020. 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 });
  40021. };
  40022. TorusKnotGeometry.prototype.copy = function (id) {
  40023. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40024. };
  40025. TorusKnotGeometry.prototype.serialize = function () {
  40026. var serializationObject = _super.prototype.serialize.call(this);
  40027. serializationObject.radius = this.radius;
  40028. serializationObject.tube = this.tube;
  40029. serializationObject.radialSegments = this.radialSegments;
  40030. serializationObject.tubularSegments = this.tubularSegments;
  40031. serializationObject.p = this.p;
  40032. serializationObject.q = this.q;
  40033. return serializationObject;
  40034. };
  40035. ;
  40036. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40037. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40038. return null; // null since geometry could be something else than a ground...
  40039. }
  40040. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40041. if (BABYLON.Tags) {
  40042. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40043. }
  40044. scene.pushGeometry(torusKnot, true);
  40045. return torusKnot;
  40046. };
  40047. return TorusKnotGeometry;
  40048. }(_PrimitiveGeometry));
  40049. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40050. //}
  40051. })(BABYLON || (BABYLON = {}));
  40052. //# sourceMappingURL=babylon.geometry.js.map
  40053. var BABYLON;
  40054. (function (BABYLON) {
  40055. /**
  40056. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40057. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40058. */
  40059. var PostProcessManager = /** @class */ (function () {
  40060. /**
  40061. * Creates a new instance PostProcess
  40062. * @param scene The scene that the post process is associated with.
  40063. */
  40064. function PostProcessManager(scene) {
  40065. this._vertexBuffers = {};
  40066. this._scene = scene;
  40067. }
  40068. PostProcessManager.prototype._prepareBuffers = function () {
  40069. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40070. return;
  40071. }
  40072. // VBO
  40073. var vertices = [];
  40074. vertices.push(1, 1);
  40075. vertices.push(-1, 1);
  40076. vertices.push(-1, -1);
  40077. vertices.push(1, -1);
  40078. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40079. this._buildIndexBuffer();
  40080. };
  40081. PostProcessManager.prototype._buildIndexBuffer = function () {
  40082. // Indices
  40083. var indices = [];
  40084. indices.push(0);
  40085. indices.push(1);
  40086. indices.push(2);
  40087. indices.push(0);
  40088. indices.push(2);
  40089. indices.push(3);
  40090. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40091. };
  40092. /**
  40093. * Rebuilds the vertex buffers of the manager.
  40094. */
  40095. PostProcessManager.prototype._rebuild = function () {
  40096. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40097. if (!vb) {
  40098. return;
  40099. }
  40100. vb._rebuild();
  40101. this._buildIndexBuffer();
  40102. };
  40103. // Methods
  40104. /**
  40105. * Prepares a frame to be run through a post process.
  40106. * @param sourceTexture The input texture to the post procesess. (default: null)
  40107. * @param postProcesses An array of post processes to be run. (default: null)
  40108. * @returns True if the post processes were able to be run.
  40109. */
  40110. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40111. if (sourceTexture === void 0) { sourceTexture = null; }
  40112. if (postProcesses === void 0) { postProcesses = null; }
  40113. var camera = this._scene.activeCamera;
  40114. if (!camera) {
  40115. return false;
  40116. }
  40117. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40118. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40119. return false;
  40120. }
  40121. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40122. return true;
  40123. };
  40124. /**
  40125. * Manually render a set of post processes to a texture.
  40126. * @param postProcesses An array of post processes to be run.
  40127. * @param targetTexture The target texture to render to.
  40128. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40129. */
  40130. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40131. if (targetTexture === void 0) { targetTexture = null; }
  40132. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40133. var engine = this._scene.getEngine();
  40134. for (var index = 0; index < postProcesses.length; index++) {
  40135. if (index < postProcesses.length - 1) {
  40136. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40137. }
  40138. else {
  40139. if (targetTexture) {
  40140. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40141. }
  40142. else {
  40143. engine.restoreDefaultFramebuffer();
  40144. }
  40145. }
  40146. var pp = postProcesses[index];
  40147. var effect = pp.apply();
  40148. if (effect) {
  40149. pp.onBeforeRenderObservable.notifyObservers(effect);
  40150. // VBOs
  40151. this._prepareBuffers();
  40152. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40153. // Draw order
  40154. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40155. pp.onAfterRenderObservable.notifyObservers(effect);
  40156. }
  40157. }
  40158. // Restore depth buffer
  40159. engine.setDepthBuffer(true);
  40160. engine.setDepthWrite(true);
  40161. };
  40162. /**
  40163. * Finalize the result of the output of the postprocesses.
  40164. * @param doNotPresent If true the result will not be displayed to the screen.
  40165. * @param targetTexture The target texture to render to.
  40166. * @param faceIndex The index of the face to bind the target texture to.
  40167. * @param postProcesses The array of post processes to render.
  40168. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40169. */
  40170. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40171. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40172. var camera = this._scene.activeCamera;
  40173. if (!camera) {
  40174. return;
  40175. }
  40176. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40177. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40178. return;
  40179. }
  40180. var engine = this._scene.getEngine();
  40181. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40182. var pp = postProcesses[index];
  40183. if (index < len - 1) {
  40184. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40185. }
  40186. else {
  40187. if (targetTexture) {
  40188. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40189. pp._outputTexture = targetTexture;
  40190. }
  40191. else {
  40192. engine.restoreDefaultFramebuffer();
  40193. pp._outputTexture = null;
  40194. }
  40195. }
  40196. if (doNotPresent) {
  40197. break;
  40198. }
  40199. var effect = pp.apply();
  40200. if (effect) {
  40201. pp.onBeforeRenderObservable.notifyObservers(effect);
  40202. // VBOs
  40203. this._prepareBuffers();
  40204. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40205. // Draw order
  40206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40207. pp.onAfterRenderObservable.notifyObservers(effect);
  40208. }
  40209. }
  40210. // Restore states
  40211. engine.setDepthBuffer(true);
  40212. engine.setDepthWrite(true);
  40213. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40214. };
  40215. /**
  40216. * Disposes of the post process manager.
  40217. */
  40218. PostProcessManager.prototype.dispose = function () {
  40219. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40220. if (buffer) {
  40221. buffer.dispose();
  40222. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40223. }
  40224. if (this._indexBuffer) {
  40225. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40226. this._indexBuffer = null;
  40227. }
  40228. };
  40229. return PostProcessManager;
  40230. }());
  40231. BABYLON.PostProcessManager = PostProcessManager;
  40232. })(BABYLON || (BABYLON = {}));
  40233. //# sourceMappingURL=babylon.postProcessManager.js.map
  40234. var BABYLON;
  40235. (function (BABYLON) {
  40236. /**
  40237. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40238. */
  40239. var PerformanceMonitor = /** @class */ (function () {
  40240. /**
  40241. * constructor
  40242. * @param frameSampleSize The number of samples required to saturate the sliding window
  40243. */
  40244. function PerformanceMonitor(frameSampleSize) {
  40245. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40246. this._enabled = true;
  40247. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40248. }
  40249. /**
  40250. * Samples current frame
  40251. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40252. */
  40253. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40254. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40255. if (!this._enabled)
  40256. return;
  40257. if (this._lastFrameTimeMs != null) {
  40258. var dt = timeMs - this._lastFrameTimeMs;
  40259. this._rollingFrameTime.add(dt);
  40260. }
  40261. this._lastFrameTimeMs = timeMs;
  40262. };
  40263. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40264. /**
  40265. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40266. * @return Average frame time in milliseconds
  40267. */
  40268. get: function () {
  40269. return this._rollingFrameTime.average;
  40270. },
  40271. enumerable: true,
  40272. configurable: true
  40273. });
  40274. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40275. /**
  40276. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40277. * @return Frame time variance in milliseconds squared
  40278. */
  40279. get: function () {
  40280. return this._rollingFrameTime.variance;
  40281. },
  40282. enumerable: true,
  40283. configurable: true
  40284. });
  40285. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40286. /**
  40287. * Returns the frame time of the most recent frame
  40288. * @return Frame time in milliseconds
  40289. */
  40290. get: function () {
  40291. return this._rollingFrameTime.history(0);
  40292. },
  40293. enumerable: true,
  40294. configurable: true
  40295. });
  40296. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40297. /**
  40298. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40299. * @return Framerate in frames per second
  40300. */
  40301. get: function () {
  40302. return 1000.0 / this._rollingFrameTime.average;
  40303. },
  40304. enumerable: true,
  40305. configurable: true
  40306. });
  40307. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40308. /**
  40309. * Returns the average framerate in frames per second using the most recent frame time
  40310. * @return Framerate in frames per second
  40311. */
  40312. get: function () {
  40313. var history = this._rollingFrameTime.history(0);
  40314. if (history === 0) {
  40315. return 0;
  40316. }
  40317. return 1000.0 / history;
  40318. },
  40319. enumerable: true,
  40320. configurable: true
  40321. });
  40322. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40323. /**
  40324. * Returns true if enough samples have been taken to completely fill the sliding window
  40325. * @return true if saturated
  40326. */
  40327. get: function () {
  40328. return this._rollingFrameTime.isSaturated();
  40329. },
  40330. enumerable: true,
  40331. configurable: true
  40332. });
  40333. /**
  40334. * Enables contributions to the sliding window sample set
  40335. */
  40336. PerformanceMonitor.prototype.enable = function () {
  40337. this._enabled = true;
  40338. };
  40339. /**
  40340. * Disables contributions to the sliding window sample set
  40341. * Samples will not be interpolated over the disabled period
  40342. */
  40343. PerformanceMonitor.prototype.disable = function () {
  40344. this._enabled = false;
  40345. //clear last sample to avoid interpolating over the disabled period when next enabled
  40346. this._lastFrameTimeMs = null;
  40347. };
  40348. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40349. /**
  40350. * Returns true if sampling is enabled
  40351. * @return true if enabled
  40352. */
  40353. get: function () {
  40354. return this._enabled;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. /**
  40360. * Resets performance monitor
  40361. */
  40362. PerformanceMonitor.prototype.reset = function () {
  40363. //clear last sample to avoid interpolating over the disabled period when next enabled
  40364. this._lastFrameTimeMs = null;
  40365. //wipe record
  40366. this._rollingFrameTime.reset();
  40367. };
  40368. return PerformanceMonitor;
  40369. }());
  40370. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40371. /**
  40372. * RollingAverage
  40373. *
  40374. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40375. */
  40376. var RollingAverage = /** @class */ (function () {
  40377. /**
  40378. * constructor
  40379. * @param length The number of samples required to saturate the sliding window
  40380. */
  40381. function RollingAverage(length) {
  40382. this._samples = new Array(length);
  40383. this.reset();
  40384. }
  40385. /**
  40386. * Adds a sample to the sample set
  40387. * @param v The sample value
  40388. */
  40389. RollingAverage.prototype.add = function (v) {
  40390. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40391. var delta;
  40392. //we need to check if we've already wrapped round
  40393. if (this.isSaturated()) {
  40394. //remove bottom of stack from mean
  40395. var bottomValue = this._samples[this._pos];
  40396. delta = bottomValue - this.average;
  40397. this.average -= delta / (this._sampleCount - 1);
  40398. this._m2 -= delta * (bottomValue - this.average);
  40399. }
  40400. else {
  40401. this._sampleCount++;
  40402. }
  40403. //add new value to mean
  40404. delta = v - this.average;
  40405. this.average += delta / (this._sampleCount);
  40406. this._m2 += delta * (v - this.average);
  40407. //set the new variance
  40408. this.variance = this._m2 / (this._sampleCount - 1);
  40409. this._samples[this._pos] = v;
  40410. this._pos++;
  40411. this._pos %= this._samples.length; //positive wrap around
  40412. };
  40413. /**
  40414. * Returns previously added values or null if outside of history or outside the sliding window domain
  40415. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40416. * @return Value previously recorded with add() or null if outside of range
  40417. */
  40418. RollingAverage.prototype.history = function (i) {
  40419. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40420. return 0;
  40421. }
  40422. var i0 = this._wrapPosition(this._pos - 1.0);
  40423. return this._samples[this._wrapPosition(i0 - i)];
  40424. };
  40425. /**
  40426. * Returns true if enough samples have been taken to completely fill the sliding window
  40427. * @return true if sample-set saturated
  40428. */
  40429. RollingAverage.prototype.isSaturated = function () {
  40430. return this._sampleCount >= this._samples.length;
  40431. };
  40432. /**
  40433. * Resets the rolling average (equivalent to 0 samples taken so far)
  40434. */
  40435. RollingAverage.prototype.reset = function () {
  40436. this.average = 0;
  40437. this.variance = 0;
  40438. this._sampleCount = 0;
  40439. this._pos = 0;
  40440. this._m2 = 0;
  40441. };
  40442. /**
  40443. * Wraps a value around the sample range boundaries
  40444. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40445. * @return Wrapped position in sample range
  40446. */
  40447. RollingAverage.prototype._wrapPosition = function (i) {
  40448. var max = this._samples.length;
  40449. return ((i % max) + max) % max;
  40450. };
  40451. return RollingAverage;
  40452. }());
  40453. BABYLON.RollingAverage = RollingAverage;
  40454. })(BABYLON || (BABYLON = {}));
  40455. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40456. var BABYLON;
  40457. (function (BABYLON) {
  40458. /**
  40459. * This groups together the common properties used for image processing either in direct forward pass
  40460. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40461. * or not.
  40462. */
  40463. var ImageProcessingConfiguration = /** @class */ (function () {
  40464. function ImageProcessingConfiguration() {
  40465. /**
  40466. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40467. */
  40468. this.colorCurves = new BABYLON.ColorCurves();
  40469. this._colorCurvesEnabled = false;
  40470. this._colorGradingEnabled = false;
  40471. this._colorGradingWithGreenDepth = true;
  40472. this._colorGradingBGR = true;
  40473. this._exposure = 1.0;
  40474. this._toneMappingEnabled = false;
  40475. this._contrast = 1.0;
  40476. /**
  40477. * Vignette stretch size.
  40478. */
  40479. this.vignetteStretch = 0;
  40480. /**
  40481. * Vignette centre X Offset.
  40482. */
  40483. this.vignetteCentreX = 0;
  40484. /**
  40485. * Vignette centre Y Offset.
  40486. */
  40487. this.vignetteCentreY = 0;
  40488. /**
  40489. * Vignette weight or intensity of the vignette effect.
  40490. */
  40491. this.vignetteWeight = 1.5;
  40492. /**
  40493. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40494. * if vignetteEnabled is set to true.
  40495. */
  40496. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40497. /**
  40498. * Camera field of view used by the Vignette effect.
  40499. */
  40500. this.vignetteCameraFov = 0.5;
  40501. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40502. this._vignetteEnabled = false;
  40503. this._applyByPostProcess = false;
  40504. this._isEnabled = true;
  40505. /**
  40506. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40507. */
  40508. this.onUpdateParameters = new BABYLON.Observable();
  40509. }
  40510. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40511. /**
  40512. * Gets wether the color curves effect is enabled.
  40513. */
  40514. get: function () {
  40515. return this._colorCurvesEnabled;
  40516. },
  40517. /**
  40518. * Sets wether the color curves effect is enabled.
  40519. */
  40520. set: function (value) {
  40521. if (this._colorCurvesEnabled === value) {
  40522. return;
  40523. }
  40524. this._colorCurvesEnabled = value;
  40525. this._updateParameters();
  40526. },
  40527. enumerable: true,
  40528. configurable: true
  40529. });
  40530. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40531. /**
  40532. * Gets wether the color grading effect is enabled.
  40533. */
  40534. get: function () {
  40535. return this._colorGradingEnabled;
  40536. },
  40537. /**
  40538. * Sets wether the color grading effect is enabled.
  40539. */
  40540. set: function (value) {
  40541. if (this._colorGradingEnabled === value) {
  40542. return;
  40543. }
  40544. this._colorGradingEnabled = value;
  40545. this._updateParameters();
  40546. },
  40547. enumerable: true,
  40548. configurable: true
  40549. });
  40550. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40551. /**
  40552. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40553. */
  40554. get: function () {
  40555. return this._colorGradingWithGreenDepth;
  40556. },
  40557. /**
  40558. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40559. */
  40560. set: function (value) {
  40561. if (this._colorGradingWithGreenDepth === value) {
  40562. return;
  40563. }
  40564. this._colorGradingWithGreenDepth = value;
  40565. this._updateParameters();
  40566. },
  40567. enumerable: true,
  40568. configurable: true
  40569. });
  40570. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40571. /**
  40572. * Gets wether the color grading texture contains BGR values.
  40573. */
  40574. get: function () {
  40575. return this._colorGradingBGR;
  40576. },
  40577. /**
  40578. * Sets wether the color grading texture contains BGR values.
  40579. */
  40580. set: function (value) {
  40581. if (this._colorGradingBGR === value) {
  40582. return;
  40583. }
  40584. this._colorGradingBGR = value;
  40585. this._updateParameters();
  40586. },
  40587. enumerable: true,
  40588. configurable: true
  40589. });
  40590. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40591. /**
  40592. * Gets the Exposure used in the effect.
  40593. */
  40594. get: function () {
  40595. return this._exposure;
  40596. },
  40597. /**
  40598. * Sets the Exposure used in the effect.
  40599. */
  40600. set: function (value) {
  40601. if (this._exposure === value) {
  40602. return;
  40603. }
  40604. this._exposure = value;
  40605. this._updateParameters();
  40606. },
  40607. enumerable: true,
  40608. configurable: true
  40609. });
  40610. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40611. /**
  40612. * Gets wether the tone mapping effect is enabled.
  40613. */
  40614. get: function () {
  40615. return this._toneMappingEnabled;
  40616. },
  40617. /**
  40618. * Sets wether the tone mapping effect is enabled.
  40619. */
  40620. set: function (value) {
  40621. if (this._toneMappingEnabled === value) {
  40622. return;
  40623. }
  40624. this._toneMappingEnabled = value;
  40625. this._updateParameters();
  40626. },
  40627. enumerable: true,
  40628. configurable: true
  40629. });
  40630. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40631. /**
  40632. * Gets the contrast used in the effect.
  40633. */
  40634. get: function () {
  40635. return this._contrast;
  40636. },
  40637. /**
  40638. * Sets the contrast used in the effect.
  40639. */
  40640. set: function (value) {
  40641. if (this._contrast === value) {
  40642. return;
  40643. }
  40644. this._contrast = value;
  40645. this._updateParameters();
  40646. },
  40647. enumerable: true,
  40648. configurable: true
  40649. });
  40650. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40651. /**
  40652. * Gets the vignette blend mode allowing different kind of effect.
  40653. */
  40654. get: function () {
  40655. return this._vignetteBlendMode;
  40656. },
  40657. /**
  40658. * Sets the vignette blend mode allowing different kind of effect.
  40659. */
  40660. set: function (value) {
  40661. if (this._vignetteBlendMode === value) {
  40662. return;
  40663. }
  40664. this._vignetteBlendMode = value;
  40665. this._updateParameters();
  40666. },
  40667. enumerable: true,
  40668. configurable: true
  40669. });
  40670. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40671. /**
  40672. * Gets wether the vignette effect is enabled.
  40673. */
  40674. get: function () {
  40675. return this._vignetteEnabled;
  40676. },
  40677. /**
  40678. * Sets wether the vignette effect is enabled.
  40679. */
  40680. set: function (value) {
  40681. if (this._vignetteEnabled === value) {
  40682. return;
  40683. }
  40684. this._vignetteEnabled = value;
  40685. this._updateParameters();
  40686. },
  40687. enumerable: true,
  40688. configurable: true
  40689. });
  40690. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40691. /**
  40692. * Gets wether the image processing is applied through a post process or not.
  40693. */
  40694. get: function () {
  40695. return this._applyByPostProcess;
  40696. },
  40697. /**
  40698. * Sets wether the image processing is applied through a post process or not.
  40699. */
  40700. set: function (value) {
  40701. if (this._applyByPostProcess === value) {
  40702. return;
  40703. }
  40704. this._applyByPostProcess = value;
  40705. this._updateParameters();
  40706. },
  40707. enumerable: true,
  40708. configurable: true
  40709. });
  40710. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40711. /**
  40712. * Gets wether the image processing is enabled or not.
  40713. */
  40714. get: function () {
  40715. return this._isEnabled;
  40716. },
  40717. /**
  40718. * Sets wether the image processing is enabled or not.
  40719. */
  40720. set: function (value) {
  40721. if (this._isEnabled === value) {
  40722. return;
  40723. }
  40724. this._isEnabled = value;
  40725. this._updateParameters();
  40726. },
  40727. enumerable: true,
  40728. configurable: true
  40729. });
  40730. /**
  40731. * Method called each time the image processing information changes requires to recompile the effect.
  40732. */
  40733. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40734. this.onUpdateParameters.notifyObservers(this);
  40735. };
  40736. ImageProcessingConfiguration.prototype.getClassName = function () {
  40737. return "ImageProcessingConfiguration";
  40738. };
  40739. /**
  40740. * Prepare the list of uniforms associated with the Image Processing effects.
  40741. * @param uniformsList The list of uniforms used in the effect
  40742. * @param defines the list of defines currently in use
  40743. */
  40744. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40745. if (defines.EXPOSURE) {
  40746. uniforms.push("exposureLinear");
  40747. }
  40748. if (defines.CONTRAST) {
  40749. uniforms.push("contrast");
  40750. }
  40751. if (defines.COLORGRADING) {
  40752. uniforms.push("colorTransformSettings");
  40753. }
  40754. if (defines.VIGNETTE) {
  40755. uniforms.push("vInverseScreenSize");
  40756. uniforms.push("vignetteSettings1");
  40757. uniforms.push("vignetteSettings2");
  40758. }
  40759. if (defines.COLORCURVES) {
  40760. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40761. }
  40762. };
  40763. /**
  40764. * Prepare the list of samplers associated with the Image Processing effects.
  40765. * @param uniformsList The list of uniforms used in the effect
  40766. * @param defines the list of defines currently in use
  40767. */
  40768. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40769. if (defines.COLORGRADING) {
  40770. samplersList.push("txColorTransform");
  40771. }
  40772. };
  40773. /**
  40774. * Prepare the list of defines associated to the shader.
  40775. * @param defines the list of defines to complete
  40776. */
  40777. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40778. if (forPostProcess === void 0) { forPostProcess = false; }
  40779. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40780. defines.VIGNETTE = false;
  40781. defines.TONEMAPPING = false;
  40782. defines.CONTRAST = false;
  40783. defines.EXPOSURE = false;
  40784. defines.COLORCURVES = false;
  40785. defines.COLORGRADING = false;
  40786. defines.COLORGRADING3D = false;
  40787. defines.IMAGEPROCESSING = false;
  40788. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40789. return;
  40790. }
  40791. defines.VIGNETTE = this.vignetteEnabled;
  40792. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40793. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40794. defines.TONEMAPPING = this.toneMappingEnabled;
  40795. defines.CONTRAST = (this.contrast !== 1.0);
  40796. defines.EXPOSURE = (this.exposure !== 1.0);
  40797. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40798. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40799. if (defines.COLORGRADING) {
  40800. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40801. }
  40802. else {
  40803. defines.COLORGRADING3D = false;
  40804. }
  40805. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40806. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40807. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40808. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40809. };
  40810. /**
  40811. * Returns true if all the image processing information are ready.
  40812. */
  40813. ImageProcessingConfiguration.prototype.isReady = function () {
  40814. // Color Grading texure can not be none blocking.
  40815. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40816. };
  40817. /**
  40818. * Binds the image processing to the shader.
  40819. * @param effect The effect to bind to
  40820. */
  40821. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40822. if (aspectRatio === void 0) { aspectRatio = 1; }
  40823. // Color Curves
  40824. if (this._colorCurvesEnabled && this.colorCurves) {
  40825. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40826. }
  40827. // Vignette
  40828. if (this._vignetteEnabled) {
  40829. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40830. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40831. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40832. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40833. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40834. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40835. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40836. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40837. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40838. var vignettePower = -2.0 * this.vignetteWeight;
  40839. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40840. }
  40841. // Exposure
  40842. effect.setFloat("exposureLinear", this.exposure);
  40843. // Contrast
  40844. effect.setFloat("contrast", this.contrast);
  40845. // Color transform settings
  40846. if (this.colorGradingTexture) {
  40847. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40848. var textureSize = this.colorGradingTexture.getSize().height;
  40849. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40850. 0.5 / textureSize, // textureOffset
  40851. textureSize, // textureSize
  40852. this.colorGradingTexture.level // weight
  40853. );
  40854. }
  40855. };
  40856. /**
  40857. * Clones the current image processing instance.
  40858. * @return The cloned image processing
  40859. */
  40860. ImageProcessingConfiguration.prototype.clone = function () {
  40861. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40862. };
  40863. /**
  40864. * Serializes the current image processing instance to a json representation.
  40865. * @return a JSON representation
  40866. */
  40867. ImageProcessingConfiguration.prototype.serialize = function () {
  40868. return BABYLON.SerializationHelper.Serialize(this);
  40869. };
  40870. /**
  40871. * Parses the image processing from a json representation.
  40872. * @param source the JSON source to parse
  40873. * @return The parsed image processing
  40874. */
  40875. ImageProcessingConfiguration.Parse = function (source) {
  40876. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40877. };
  40878. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40879. /**
  40880. * Used to apply the vignette as a mix with the pixel color.
  40881. */
  40882. get: function () {
  40883. return this._VIGNETTEMODE_MULTIPLY;
  40884. },
  40885. enumerable: true,
  40886. configurable: true
  40887. });
  40888. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40889. /**
  40890. * Used to apply the vignette as a replacement of the pixel color.
  40891. */
  40892. get: function () {
  40893. return this._VIGNETTEMODE_OPAQUE;
  40894. },
  40895. enumerable: true,
  40896. configurable: true
  40897. });
  40898. // Static constants associated to the image processing.
  40899. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40900. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40901. __decorate([
  40902. BABYLON.serializeAsColorCurves()
  40903. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40904. __decorate([
  40905. BABYLON.serialize()
  40906. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40907. __decorate([
  40908. BABYLON.serializeAsTexture()
  40909. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40910. __decorate([
  40911. BABYLON.serialize()
  40912. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40913. __decorate([
  40914. BABYLON.serialize()
  40915. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40916. __decorate([
  40917. BABYLON.serialize()
  40918. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40919. __decorate([
  40920. BABYLON.serialize()
  40921. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40922. __decorate([
  40923. BABYLON.serialize()
  40924. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40925. __decorate([
  40926. BABYLON.serialize()
  40927. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40928. __decorate([
  40929. BABYLON.serialize()
  40930. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40931. __decorate([
  40932. BABYLON.serialize()
  40933. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40934. __decorate([
  40935. BABYLON.serialize()
  40936. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40937. __decorate([
  40938. BABYLON.serialize()
  40939. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40940. __decorate([
  40941. BABYLON.serializeAsColor4()
  40942. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40943. __decorate([
  40944. BABYLON.serialize()
  40945. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40946. __decorate([
  40947. BABYLON.serialize()
  40948. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  40949. __decorate([
  40950. BABYLON.serialize()
  40951. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  40952. __decorate([
  40953. BABYLON.serialize()
  40954. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  40955. __decorate([
  40956. BABYLON.serialize()
  40957. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  40958. return ImageProcessingConfiguration;
  40959. }());
  40960. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  40961. })(BABYLON || (BABYLON = {}));
  40962. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  40963. var BABYLON;
  40964. (function (BABYLON) {
  40965. /**
  40966. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  40967. * It can help converting any input color in a desired output one. This can then be used to create effects
  40968. * from sepia, black and white to sixties or futuristic rendering...
  40969. *
  40970. * The only supported format is currently 3dl.
  40971. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  40972. */
  40973. var ColorGradingTexture = /** @class */ (function (_super) {
  40974. __extends(ColorGradingTexture, _super);
  40975. /**
  40976. * Instantiates a ColorGradingTexture from the following parameters.
  40977. *
  40978. * @param url The location of the color gradind data (currently only supporting 3dl)
  40979. * @param scene The scene the texture will be used in
  40980. */
  40981. function ColorGradingTexture(url, scene) {
  40982. var _this = _super.call(this, scene) || this;
  40983. if (!url) {
  40984. return _this;
  40985. }
  40986. _this._engine = scene.getEngine();
  40987. _this._textureMatrix = BABYLON.Matrix.Identity();
  40988. _this.name = url;
  40989. _this.url = url;
  40990. _this.hasAlpha = false;
  40991. _this.isCube = false;
  40992. _this.is3D = _this._engine.webGLVersion > 1;
  40993. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40994. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40995. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40996. _this.anisotropicFilteringLevel = 1;
  40997. _this._texture = _this._getFromCache(url, true);
  40998. if (!_this._texture) {
  40999. if (!scene.useDelayedTextureLoading) {
  41000. _this.loadTexture();
  41001. }
  41002. else {
  41003. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41004. }
  41005. }
  41006. return _this;
  41007. }
  41008. /**
  41009. * Returns the texture matrix used in most of the material.
  41010. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41011. */
  41012. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41013. return this._textureMatrix;
  41014. };
  41015. /**
  41016. * Occurs when the file being loaded is a .3dl LUT file.
  41017. */
  41018. ColorGradingTexture.prototype.load3dlTexture = function () {
  41019. var engine = this._engine;
  41020. var texture;
  41021. if (engine.webGLVersion === 1) {
  41022. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41023. }
  41024. else {
  41025. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41026. }
  41027. this._texture = texture;
  41028. var callback = function (text) {
  41029. if (typeof text !== "string") {
  41030. return;
  41031. }
  41032. var data = null;
  41033. var tempData = null;
  41034. var line;
  41035. var lines = text.split('\n');
  41036. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41037. var maxColor = 0;
  41038. for (var i = 0; i < lines.length; i++) {
  41039. line = lines[i];
  41040. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41041. continue;
  41042. if (line.indexOf('#') === 0)
  41043. continue;
  41044. var words = line.split(" ");
  41045. if (size === 0) {
  41046. // Number of space + one
  41047. size = words.length;
  41048. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41049. tempData = new Float32Array(size * size * size * 4);
  41050. continue;
  41051. }
  41052. if (size != 0) {
  41053. var r = Math.max(parseInt(words[0]), 0);
  41054. var g = Math.max(parseInt(words[1]), 0);
  41055. var b = Math.max(parseInt(words[2]), 0);
  41056. maxColor = Math.max(r, maxColor);
  41057. maxColor = Math.max(g, maxColor);
  41058. maxColor = Math.max(b, maxColor);
  41059. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41060. if (tempData) {
  41061. tempData[pixelStorageIndex + 0] = r;
  41062. tempData[pixelStorageIndex + 1] = g;
  41063. tempData[pixelStorageIndex + 2] = b;
  41064. }
  41065. pixelIndexSlice++;
  41066. if (pixelIndexSlice % size == 0) {
  41067. pixelIndexH++;
  41068. pixelIndexSlice = 0;
  41069. if (pixelIndexH % size == 0) {
  41070. pixelIndexW++;
  41071. pixelIndexH = 0;
  41072. }
  41073. }
  41074. }
  41075. }
  41076. if (tempData && data) {
  41077. for (var i = 0; i < tempData.length; i++) {
  41078. if (i > 0 && (i + 1) % 4 === 0) {
  41079. data[i] = 255;
  41080. }
  41081. else {
  41082. var value = tempData[i];
  41083. data[i] = (value / maxColor * 255);
  41084. }
  41085. }
  41086. }
  41087. if (texture.is3D) {
  41088. texture.updateSize(size, size, size);
  41089. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41090. }
  41091. else {
  41092. texture.updateSize(size * size, size);
  41093. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41094. }
  41095. };
  41096. var scene = this.getScene();
  41097. if (scene) {
  41098. scene._loadFile(this.url, callback);
  41099. }
  41100. else {
  41101. this._engine._loadFile(this.url, callback);
  41102. }
  41103. return this._texture;
  41104. };
  41105. /**
  41106. * Starts the loading process of the texture.
  41107. */
  41108. ColorGradingTexture.prototype.loadTexture = function () {
  41109. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41110. this.load3dlTexture();
  41111. }
  41112. };
  41113. /**
  41114. * Clones the color gradind texture.
  41115. */
  41116. ColorGradingTexture.prototype.clone = function () {
  41117. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41118. // Base texture
  41119. newTexture.level = this.level;
  41120. return newTexture;
  41121. };
  41122. /**
  41123. * Called during delayed load for textures.
  41124. */
  41125. ColorGradingTexture.prototype.delayLoad = function () {
  41126. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41127. return;
  41128. }
  41129. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41130. this._texture = this._getFromCache(this.url, true);
  41131. if (!this._texture) {
  41132. this.loadTexture();
  41133. }
  41134. };
  41135. /**
  41136. * Parses a color grading texture serialized by Babylon.
  41137. * @param parsedTexture The texture information being parsedTexture
  41138. * @param scene The scene to load the texture in
  41139. * @param rootUrl The root url of the data assets to load
  41140. * @return A color gradind texture
  41141. */
  41142. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41143. var texture = null;
  41144. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41145. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41146. texture.name = parsedTexture.name;
  41147. texture.level = parsedTexture.level;
  41148. }
  41149. return texture;
  41150. };
  41151. /**
  41152. * Serializes the LUT texture to json format.
  41153. */
  41154. ColorGradingTexture.prototype.serialize = function () {
  41155. if (!this.name) {
  41156. return null;
  41157. }
  41158. var serializationObject = {};
  41159. serializationObject.name = this.name;
  41160. serializationObject.level = this.level;
  41161. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41162. return serializationObject;
  41163. };
  41164. /**
  41165. * Empty line regex stored for GC.
  41166. */
  41167. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41168. return ColorGradingTexture;
  41169. }(BABYLON.BaseTexture));
  41170. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41171. })(BABYLON || (BABYLON = {}));
  41172. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41173. var BABYLON;
  41174. (function (BABYLON) {
  41175. /**
  41176. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41177. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41178. * 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;
  41179. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41180. */
  41181. var ColorCurves = /** @class */ (function () {
  41182. function ColorCurves() {
  41183. this._dirty = true;
  41184. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41185. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41186. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41187. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41188. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41189. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41190. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41191. this._globalHue = 30;
  41192. this._globalDensity = 0;
  41193. this._globalSaturation = 0;
  41194. this._globalExposure = 0;
  41195. this._highlightsHue = 30;
  41196. this._highlightsDensity = 0;
  41197. this._highlightsSaturation = 0;
  41198. this._highlightsExposure = 0;
  41199. this._midtonesHue = 30;
  41200. this._midtonesDensity = 0;
  41201. this._midtonesSaturation = 0;
  41202. this._midtonesExposure = 0;
  41203. this._shadowsHue = 30;
  41204. this._shadowsDensity = 0;
  41205. this._shadowsSaturation = 0;
  41206. this._shadowsExposure = 0;
  41207. }
  41208. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41209. /**
  41210. * Gets the global Hue value.
  41211. * 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).
  41212. */
  41213. get: function () {
  41214. return this._globalHue;
  41215. },
  41216. /**
  41217. * Sets the global Hue value.
  41218. * 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).
  41219. */
  41220. set: function (value) {
  41221. this._globalHue = value;
  41222. this._dirty = true;
  41223. },
  41224. enumerable: true,
  41225. configurable: true
  41226. });
  41227. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41228. /**
  41229. * Gets the global Density value.
  41230. * 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.
  41231. * Values less than zero provide a filter of opposite hue.
  41232. */
  41233. get: function () {
  41234. return this._globalDensity;
  41235. },
  41236. /**
  41237. * Sets the global Density value.
  41238. * 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.
  41239. * Values less than zero provide a filter of opposite hue.
  41240. */
  41241. set: function (value) {
  41242. this._globalDensity = value;
  41243. this._dirty = true;
  41244. },
  41245. enumerable: true,
  41246. configurable: true
  41247. });
  41248. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41249. /**
  41250. * Gets the global Saturation value.
  41251. * 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.
  41252. */
  41253. get: function () {
  41254. return this._globalSaturation;
  41255. },
  41256. /**
  41257. * Sets the global Saturation value.
  41258. * 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.
  41259. */
  41260. set: function (value) {
  41261. this._globalSaturation = value;
  41262. this._dirty = true;
  41263. },
  41264. enumerable: true,
  41265. configurable: true
  41266. });
  41267. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41268. /**
  41269. * Gets the highlights Hue value.
  41270. * 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).
  41271. */
  41272. get: function () {
  41273. return this._highlightsHue;
  41274. },
  41275. /**
  41276. * Sets the highlights Hue value.
  41277. * 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).
  41278. */
  41279. set: function (value) {
  41280. this._highlightsHue = value;
  41281. this._dirty = true;
  41282. },
  41283. enumerable: true,
  41284. configurable: true
  41285. });
  41286. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41287. /**
  41288. * Gets the highlights Density value.
  41289. * 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.
  41290. * Values less than zero provide a filter of opposite hue.
  41291. */
  41292. get: function () {
  41293. return this._highlightsDensity;
  41294. },
  41295. /**
  41296. * Sets the highlights Density value.
  41297. * 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.
  41298. * Values less than zero provide a filter of opposite hue.
  41299. */
  41300. set: function (value) {
  41301. this._highlightsDensity = value;
  41302. this._dirty = true;
  41303. },
  41304. enumerable: true,
  41305. configurable: true
  41306. });
  41307. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41308. /**
  41309. * Gets the highlights Saturation value.
  41310. * 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.
  41311. */
  41312. get: function () {
  41313. return this._highlightsSaturation;
  41314. },
  41315. /**
  41316. * Sets the highlights Saturation value.
  41317. * 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.
  41318. */
  41319. set: function (value) {
  41320. this._highlightsSaturation = value;
  41321. this._dirty = true;
  41322. },
  41323. enumerable: true,
  41324. configurable: true
  41325. });
  41326. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41327. /**
  41328. * Gets the highlights Exposure value.
  41329. * 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.
  41330. */
  41331. get: function () {
  41332. return this._highlightsExposure;
  41333. },
  41334. /**
  41335. * Sets the highlights Exposure value.
  41336. * 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.
  41337. */
  41338. set: function (value) {
  41339. this._highlightsExposure = value;
  41340. this._dirty = true;
  41341. },
  41342. enumerable: true,
  41343. configurable: true
  41344. });
  41345. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41346. /**
  41347. * Gets the midtones Hue value.
  41348. * 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).
  41349. */
  41350. get: function () {
  41351. return this._midtonesHue;
  41352. },
  41353. /**
  41354. * Sets the midtones Hue value.
  41355. * 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).
  41356. */
  41357. set: function (value) {
  41358. this._midtonesHue = value;
  41359. this._dirty = true;
  41360. },
  41361. enumerable: true,
  41362. configurable: true
  41363. });
  41364. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41365. /**
  41366. * Gets the midtones Density value.
  41367. * 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.
  41368. * Values less than zero provide a filter of opposite hue.
  41369. */
  41370. get: function () {
  41371. return this._midtonesDensity;
  41372. },
  41373. /**
  41374. * Sets the midtones Density value.
  41375. * 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.
  41376. * Values less than zero provide a filter of opposite hue.
  41377. */
  41378. set: function (value) {
  41379. this._midtonesDensity = value;
  41380. this._dirty = true;
  41381. },
  41382. enumerable: true,
  41383. configurable: true
  41384. });
  41385. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41386. /**
  41387. * Gets the midtones Saturation value.
  41388. * 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.
  41389. */
  41390. get: function () {
  41391. return this._midtonesSaturation;
  41392. },
  41393. /**
  41394. * Sets the midtones Saturation value.
  41395. * 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.
  41396. */
  41397. set: function (value) {
  41398. this._midtonesSaturation = value;
  41399. this._dirty = true;
  41400. },
  41401. enumerable: true,
  41402. configurable: true
  41403. });
  41404. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41405. /**
  41406. * Gets the midtones Exposure value.
  41407. * 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.
  41408. */
  41409. get: function () {
  41410. return this._midtonesExposure;
  41411. },
  41412. /**
  41413. * Sets the midtones Exposure value.
  41414. * 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.
  41415. */
  41416. set: function (value) {
  41417. this._midtonesExposure = value;
  41418. this._dirty = true;
  41419. },
  41420. enumerable: true,
  41421. configurable: true
  41422. });
  41423. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41424. /**
  41425. * Gets the shadows Hue value.
  41426. * 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).
  41427. */
  41428. get: function () {
  41429. return this._shadowsHue;
  41430. },
  41431. /**
  41432. * Sets the shadows Hue value.
  41433. * 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).
  41434. */
  41435. set: function (value) {
  41436. this._shadowsHue = value;
  41437. this._dirty = true;
  41438. },
  41439. enumerable: true,
  41440. configurable: true
  41441. });
  41442. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41443. /**
  41444. * Gets the shadows Density value.
  41445. * 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.
  41446. * Values less than zero provide a filter of opposite hue.
  41447. */
  41448. get: function () {
  41449. return this._shadowsDensity;
  41450. },
  41451. /**
  41452. * Sets the shadows Density value.
  41453. * 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.
  41454. * Values less than zero provide a filter of opposite hue.
  41455. */
  41456. set: function (value) {
  41457. this._shadowsDensity = value;
  41458. this._dirty = true;
  41459. },
  41460. enumerable: true,
  41461. configurable: true
  41462. });
  41463. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41464. /**
  41465. * Gets the shadows Saturation value.
  41466. * 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.
  41467. */
  41468. get: function () {
  41469. return this._shadowsSaturation;
  41470. },
  41471. /**
  41472. * Sets the shadows Saturation value.
  41473. * 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.
  41474. */
  41475. set: function (value) {
  41476. this._shadowsSaturation = value;
  41477. this._dirty = true;
  41478. },
  41479. enumerable: true,
  41480. configurable: true
  41481. });
  41482. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41483. /**
  41484. * Gets the shadows Exposure value.
  41485. * 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.
  41486. */
  41487. get: function () {
  41488. return this._shadowsExposure;
  41489. },
  41490. /**
  41491. * Sets the shadows Exposure value.
  41492. * 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.
  41493. */
  41494. set: function (value) {
  41495. this._shadowsExposure = value;
  41496. this._dirty = true;
  41497. },
  41498. enumerable: true,
  41499. configurable: true
  41500. });
  41501. ColorCurves.prototype.getClassName = function () {
  41502. return "ColorCurves";
  41503. };
  41504. /**
  41505. * Binds the color curves to the shader.
  41506. * @param colorCurves The color curve to bind
  41507. * @param effect The effect to bind to
  41508. */
  41509. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41510. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41511. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41512. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41513. if (colorCurves._dirty) {
  41514. colorCurves._dirty = false;
  41515. // Fill in global info.
  41516. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41517. // Compute highlights info.
  41518. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41519. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41520. // Compute midtones info.
  41521. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41522. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41523. // Compute shadows info.
  41524. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41525. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41526. // Compute deltas (neutral is midtones).
  41527. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41528. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41529. }
  41530. if (effect) {
  41531. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41532. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41533. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41534. }
  41535. };
  41536. /**
  41537. * Prepare the list of uniforms associated with the ColorCurves effects.
  41538. * @param uniformsList The list of uniforms used in the effect
  41539. */
  41540. ColorCurves.PrepareUniforms = function (uniformsList) {
  41541. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41542. };
  41543. /**
  41544. * Returns color grading data based on a hue, density, saturation and exposure value.
  41545. * @param filterHue The hue of the color filter.
  41546. * @param filterDensity The density of the color filter.
  41547. * @param saturation The saturation.
  41548. * @param exposure The exposure.
  41549. * @param result The result data container.
  41550. */
  41551. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41552. if (hue == null) {
  41553. return;
  41554. }
  41555. hue = ColorCurves.clamp(hue, 0, 360);
  41556. density = ColorCurves.clamp(density, -100, 100);
  41557. saturation = ColorCurves.clamp(saturation, -100, 100);
  41558. exposure = ColorCurves.clamp(exposure, -100, 100);
  41559. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41560. // so that the maximum filter density is only 50% control. This provides fine control
  41561. // for small values and reasonable range.
  41562. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41563. density *= 0.5;
  41564. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41565. if (density < 0) {
  41566. density *= -1;
  41567. hue = (hue + 180) % 360;
  41568. }
  41569. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41570. result.scaleToRef(2, result);
  41571. result.a = 1 + 0.01 * saturation;
  41572. };
  41573. /**
  41574. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41575. * @param value The input slider value in range [-100,100].
  41576. * @returns Adjusted value.
  41577. */
  41578. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41579. value /= 100;
  41580. var x = Math.abs(value);
  41581. x = Math.pow(x, 2);
  41582. if (value < 0) {
  41583. x *= -1;
  41584. }
  41585. x *= 100;
  41586. return x;
  41587. };
  41588. /**
  41589. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41590. * @param hue The hue (H) input.
  41591. * @param saturation The saturation (S) input.
  41592. * @param brightness The brightness (B) input.
  41593. * @result An RGBA color represented as Vector4.
  41594. */
  41595. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41596. var h = ColorCurves.clamp(hue, 0, 360);
  41597. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41598. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41599. if (s === 0) {
  41600. result.r = v;
  41601. result.g = v;
  41602. result.b = v;
  41603. }
  41604. else {
  41605. // sector 0 to 5
  41606. h /= 60;
  41607. var i = Math.floor(h);
  41608. // fractional part of h
  41609. var f = h - i;
  41610. var p = v * (1 - s);
  41611. var q = v * (1 - s * f);
  41612. var t = v * (1 - s * (1 - f));
  41613. switch (i) {
  41614. case 0:
  41615. result.r = v;
  41616. result.g = t;
  41617. result.b = p;
  41618. break;
  41619. case 1:
  41620. result.r = q;
  41621. result.g = v;
  41622. result.b = p;
  41623. break;
  41624. case 2:
  41625. result.r = p;
  41626. result.g = v;
  41627. result.b = t;
  41628. break;
  41629. case 3:
  41630. result.r = p;
  41631. result.g = q;
  41632. result.b = v;
  41633. break;
  41634. case 4:
  41635. result.r = t;
  41636. result.g = p;
  41637. result.b = v;
  41638. break;
  41639. default: // case 5:
  41640. result.r = v;
  41641. result.g = p;
  41642. result.b = q;
  41643. break;
  41644. }
  41645. }
  41646. result.a = 1;
  41647. };
  41648. /**
  41649. * Returns a value clamped between min and max
  41650. * @param value The value to clamp
  41651. * @param min The minimum of value
  41652. * @param max The maximum of value
  41653. * @returns The clamped value.
  41654. */
  41655. ColorCurves.clamp = function (value, min, max) {
  41656. return Math.min(Math.max(value, min), max);
  41657. };
  41658. /**
  41659. * Clones the current color curve instance.
  41660. * @return The cloned curves
  41661. */
  41662. ColorCurves.prototype.clone = function () {
  41663. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41664. };
  41665. /**
  41666. * Serializes the current color curve instance to a json representation.
  41667. * @return a JSON representation
  41668. */
  41669. ColorCurves.prototype.serialize = function () {
  41670. return BABYLON.SerializationHelper.Serialize(this);
  41671. };
  41672. /**
  41673. * Parses the color curve from a json representation.
  41674. * @param source the JSON source to parse
  41675. * @return The parsed curves
  41676. */
  41677. ColorCurves.Parse = function (source) {
  41678. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41679. };
  41680. __decorate([
  41681. BABYLON.serialize()
  41682. ], ColorCurves.prototype, "_globalHue", void 0);
  41683. __decorate([
  41684. BABYLON.serialize()
  41685. ], ColorCurves.prototype, "_globalDensity", void 0);
  41686. __decorate([
  41687. BABYLON.serialize()
  41688. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41689. __decorate([
  41690. BABYLON.serialize()
  41691. ], ColorCurves.prototype, "_globalExposure", void 0);
  41692. __decorate([
  41693. BABYLON.serialize()
  41694. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41695. __decorate([
  41696. BABYLON.serialize()
  41697. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41698. __decorate([
  41699. BABYLON.serialize()
  41700. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41701. __decorate([
  41702. BABYLON.serialize()
  41703. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41704. __decorate([
  41705. BABYLON.serialize()
  41706. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41707. __decorate([
  41708. BABYLON.serialize()
  41709. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41710. __decorate([
  41711. BABYLON.serialize()
  41712. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41713. __decorate([
  41714. BABYLON.serialize()
  41715. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41716. return ColorCurves;
  41717. }());
  41718. BABYLON.ColorCurves = ColorCurves;
  41719. })(BABYLON || (BABYLON = {}));
  41720. //# sourceMappingURL=babylon.colorCurves.js.map
  41721. //# sourceMappingURL=babylon.behavior.js.map
  41722. var BABYLON;
  41723. (function (BABYLON) {
  41724. /**
  41725. * "Static Class" containing the most commonly used helper while dealing with material for
  41726. * rendering purpose.
  41727. *
  41728. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41729. *
  41730. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41731. */
  41732. var MaterialHelper = /** @class */ (function () {
  41733. function MaterialHelper() {
  41734. }
  41735. /**
  41736. * Bind the current view position to an effect.
  41737. * @param effect The effect to be bound
  41738. * @param scene The scene the eyes position is used from
  41739. */
  41740. MaterialHelper.BindEyePosition = function (effect, scene) {
  41741. if (scene._forcedViewPosition) {
  41742. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41743. return;
  41744. }
  41745. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41746. };
  41747. /**
  41748. * Helps preparing the defines values about the UVs in used in the effect.
  41749. * UVs are shared as much as we can accross chanels in the shaders.
  41750. * @param texture The texture we are preparing the UVs for
  41751. * @param defines The defines to update
  41752. * @param key The chanel key "diffuse", "specular"... used in the shader
  41753. */
  41754. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41755. defines._needUVs = true;
  41756. defines[key] = true;
  41757. if (texture.getTextureMatrix().isIdentity(true)) {
  41758. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41759. if (texture.coordinatesIndex === 0) {
  41760. defines["MAINUV1"] = true;
  41761. }
  41762. else {
  41763. defines["MAINUV2"] = true;
  41764. }
  41765. }
  41766. else {
  41767. defines[key + "DIRECTUV"] = 0;
  41768. }
  41769. };
  41770. /**
  41771. * Binds a texture matrix value to its corrsponding uniform
  41772. * @param texture The texture to bind the matrix for
  41773. * @param uniformBuffer The uniform buffer receivin the data
  41774. * @param key The chanel key "diffuse", "specular"... used in the shader
  41775. */
  41776. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41777. var matrix = texture.getTextureMatrix();
  41778. if (!matrix.isIdentity(true)) {
  41779. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41780. }
  41781. };
  41782. /**
  41783. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41784. * @param mesh defines the current mesh
  41785. * @param scene defines the current scene
  41786. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41787. * @param pointsCloud defines if point cloud rendering has to be turned on
  41788. * @param fogEnabled defines if fog has to be turned on
  41789. * @param alphaTest defines if alpha testing has to be turned on
  41790. * @param defines defines the current list of defines
  41791. */
  41792. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41793. if (defines._areMiscDirty) {
  41794. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41795. defines["POINTSIZE"] = pointsCloud;
  41796. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41797. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41798. defines["ALPHATEST"] = alphaTest;
  41799. }
  41800. };
  41801. /**
  41802. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41803. * @param scene defines the current scene
  41804. * @param engine defines the current engine
  41805. * @param defines specifies the list of active defines
  41806. * @param useInstances defines if instances have to be turned on
  41807. * @param useClipPlane defines if clip plane have to be turned on
  41808. */
  41809. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41810. if (useClipPlane === void 0) { useClipPlane = null; }
  41811. var changed = false;
  41812. if (useClipPlane == null) {
  41813. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41814. }
  41815. if (defines["CLIPPLANE"] !== useClipPlane) {
  41816. defines["CLIPPLANE"] = useClipPlane;
  41817. changed = true;
  41818. }
  41819. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41820. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41821. changed = true;
  41822. }
  41823. if (defines["INSTANCES"] !== useInstances) {
  41824. defines["INSTANCES"] = useInstances;
  41825. changed = true;
  41826. }
  41827. if (changed) {
  41828. defines.markAsUnprocessed();
  41829. }
  41830. };
  41831. /**
  41832. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41833. * @param mesh The mesh containing the geometry data we will draw
  41834. * @param defines The defines to update
  41835. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41836. * @param useBones Precise whether bones should be used or not (override mesh info)
  41837. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41838. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41839. * @returns false if defines are considered not dirty and have not been checked
  41840. */
  41841. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41842. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41843. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41844. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41845. return false;
  41846. }
  41847. defines._normals = defines._needNormals;
  41848. defines._uvs = defines._needUVs;
  41849. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41850. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41851. defines["TANGENT"] = true;
  41852. }
  41853. if (defines._needUVs) {
  41854. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41855. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41856. }
  41857. else {
  41858. defines["UV1"] = false;
  41859. defines["UV2"] = false;
  41860. }
  41861. if (useVertexColor) {
  41862. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41863. defines["VERTEXCOLOR"] = hasVertexColors;
  41864. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41865. }
  41866. if (useBones) {
  41867. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41868. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41869. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41870. }
  41871. else {
  41872. defines["NUM_BONE_INFLUENCERS"] = 0;
  41873. defines["BonesPerMesh"] = 0;
  41874. }
  41875. }
  41876. if (useMorphTargets) {
  41877. var manager = mesh.morphTargetManager;
  41878. if (manager) {
  41879. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41880. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41881. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41882. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41883. }
  41884. else {
  41885. defines["MORPHTARGETS_TANGENT"] = false;
  41886. defines["MORPHTARGETS_NORMAL"] = false;
  41887. defines["MORPHTARGETS"] = false;
  41888. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41889. }
  41890. }
  41891. return true;
  41892. };
  41893. /**
  41894. * Prepares the defines related to the light information passed in parameter
  41895. * @param scene The scene we are intending to draw
  41896. * @param mesh The mesh the effect is compiling for
  41897. * @param defines The defines to update
  41898. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41899. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41900. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41901. * @returns true if normals will be required for the rest of the effect
  41902. */
  41903. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41904. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41905. if (disableLighting === void 0) { disableLighting = false; }
  41906. if (!defines._areLightsDirty) {
  41907. return defines._needNormals;
  41908. }
  41909. var lightIndex = 0;
  41910. var needNormals = false;
  41911. var needRebuild = false;
  41912. var lightmapMode = false;
  41913. var shadowEnabled = false;
  41914. var specularEnabled = false;
  41915. if (scene.lightsEnabled && !disableLighting) {
  41916. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41917. var light = _a[_i];
  41918. needNormals = true;
  41919. if (defines["LIGHT" + lightIndex] === undefined) {
  41920. needRebuild = true;
  41921. }
  41922. defines["LIGHT" + lightIndex] = true;
  41923. defines["SPOTLIGHT" + lightIndex] = false;
  41924. defines["HEMILIGHT" + lightIndex] = false;
  41925. defines["POINTLIGHT" + lightIndex] = false;
  41926. defines["DIRLIGHT" + lightIndex] = false;
  41927. var type;
  41928. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41929. type = "SPOTLIGHT" + lightIndex;
  41930. var spotLight = light;
  41931. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41932. }
  41933. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41934. type = "HEMILIGHT" + lightIndex;
  41935. }
  41936. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41937. type = "POINTLIGHT" + lightIndex;
  41938. }
  41939. else {
  41940. type = "DIRLIGHT" + lightIndex;
  41941. }
  41942. defines[type] = true;
  41943. // Specular
  41944. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41945. specularEnabled = true;
  41946. }
  41947. // Shadows
  41948. defines["SHADOW" + lightIndex] = false;
  41949. defines["SHADOWPCF" + lightIndex] = false;
  41950. defines["SHADOWPCSS" + lightIndex] = false;
  41951. defines["SHADOWPOISSON" + lightIndex] = false;
  41952. defines["SHADOWESM" + lightIndex] = false;
  41953. defines["SHADOWCUBE" + lightIndex] = false;
  41954. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41955. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41956. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41957. var shadowGenerator = light.getShadowGenerator();
  41958. if (shadowGenerator) {
  41959. shadowEnabled = true;
  41960. shadowGenerator.prepareDefines(defines, lightIndex);
  41961. }
  41962. }
  41963. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41964. lightmapMode = true;
  41965. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41966. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41967. }
  41968. else {
  41969. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41970. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41971. }
  41972. lightIndex++;
  41973. if (lightIndex === maxSimultaneousLights)
  41974. break;
  41975. }
  41976. }
  41977. defines["SPECULARTERM"] = specularEnabled;
  41978. defines["SHADOWS"] = shadowEnabled;
  41979. // Resetting all other lights if any
  41980. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41981. if (defines["LIGHT" + index] !== undefined) {
  41982. defines["LIGHT" + index] = false;
  41983. defines["HEMILIGHT" + lightIndex] = false;
  41984. defines["POINTLIGHT" + lightIndex] = false;
  41985. defines["DIRLIGHT" + lightIndex] = false;
  41986. defines["SPOTLIGHT" + lightIndex] = false;
  41987. defines["SHADOW" + lightIndex] = false;
  41988. }
  41989. }
  41990. var caps = scene.getEngine().getCaps();
  41991. if (defines["SHADOWFLOAT"] === undefined) {
  41992. needRebuild = true;
  41993. }
  41994. defines["SHADOWFLOAT"] = shadowEnabled &&
  41995. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41996. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41997. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41998. if (needRebuild) {
  41999. defines.rebuild();
  42000. }
  42001. return needNormals;
  42002. };
  42003. /**
  42004. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42005. * that won t be acctive due to defines being turned off.
  42006. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42007. * @param samplersList The samplers list
  42008. * @param defines The defines helping in the list generation
  42009. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42010. */
  42011. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42012. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42013. var uniformsList;
  42014. var uniformBuffersList = null;
  42015. if (uniformsListOrOptions.uniformsNames) {
  42016. var options = uniformsListOrOptions;
  42017. uniformsList = options.uniformsNames;
  42018. uniformBuffersList = options.uniformBuffersNames;
  42019. samplersList = options.samplers;
  42020. defines = options.defines;
  42021. maxSimultaneousLights = options.maxSimultaneousLights;
  42022. }
  42023. else {
  42024. uniformsList = uniformsListOrOptions;
  42025. if (!samplersList) {
  42026. samplersList = [];
  42027. }
  42028. }
  42029. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42030. if (!defines["LIGHT" + lightIndex]) {
  42031. break;
  42032. }
  42033. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42034. if (uniformBuffersList) {
  42035. uniformBuffersList.push("Light" + lightIndex);
  42036. }
  42037. samplersList.push("shadowSampler" + lightIndex);
  42038. samplersList.push("depthSampler" + lightIndex);
  42039. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42040. samplersList.push("projectionLightSampler" + lightIndex);
  42041. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42042. }
  42043. }
  42044. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42045. uniformsList.push("morphTargetInfluences");
  42046. }
  42047. };
  42048. /**
  42049. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42050. * @param defines The defines to update while falling back
  42051. * @param fallbacks The authorized effect fallbacks
  42052. * @param maxSimultaneousLights The maximum number of lights allowed
  42053. * @param rank the current rank of the Effect
  42054. * @returns The newly affected rank
  42055. */
  42056. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42057. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42058. if (rank === void 0) { rank = 0; }
  42059. var lightFallbackRank = 0;
  42060. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42061. if (!defines["LIGHT" + lightIndex]) {
  42062. break;
  42063. }
  42064. if (lightIndex > 0) {
  42065. lightFallbackRank = rank + lightIndex;
  42066. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42067. }
  42068. if (!defines["SHADOWS"]) {
  42069. if (defines["SHADOW" + lightIndex]) {
  42070. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42071. }
  42072. if (defines["SHADOWPCF" + lightIndex]) {
  42073. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42074. }
  42075. if (defines["SHADOWPCSS" + lightIndex]) {
  42076. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42077. }
  42078. if (defines["SHADOWPOISSON" + lightIndex]) {
  42079. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42080. }
  42081. if (defines["SHADOWESM" + lightIndex]) {
  42082. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42083. }
  42084. }
  42085. }
  42086. return lightFallbackRank++;
  42087. };
  42088. /**
  42089. * Prepares the list of attributes required for morph targets according to the effect defines.
  42090. * @param attribs The current list of supported attribs
  42091. * @param mesh The mesh to prepare the morph targets attributes for
  42092. * @param defines The current Defines of the effect
  42093. */
  42094. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42095. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42096. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42097. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42098. var manager = mesh.morphTargetManager;
  42099. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42100. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42101. for (var index = 0; index < influencers; index++) {
  42102. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42103. if (normal) {
  42104. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42105. }
  42106. if (tangent) {
  42107. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42108. }
  42109. if (attribs.length > maxAttributesCount) {
  42110. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42111. }
  42112. }
  42113. }
  42114. };
  42115. /**
  42116. * Prepares the list of attributes required for bones according to the effect defines.
  42117. * @param attribs The current list of supported attribs
  42118. * @param mesh The mesh to prepare the bones attributes for
  42119. * @param defines The current Defines of the effect
  42120. * @param fallbacks The current efffect fallback strategy
  42121. */
  42122. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42123. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42124. fallbacks.addCPUSkinningFallback(0, mesh);
  42125. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42126. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42127. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42128. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42129. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42130. }
  42131. }
  42132. };
  42133. /**
  42134. * Prepares the list of attributes required for instances according to the effect defines.
  42135. * @param attribs The current list of supported attribs
  42136. * @param defines The current Defines of the effect
  42137. */
  42138. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42139. if (defines["INSTANCES"]) {
  42140. attribs.push("world0");
  42141. attribs.push("world1");
  42142. attribs.push("world2");
  42143. attribs.push("world3");
  42144. }
  42145. };
  42146. /**
  42147. * Binds the light shadow information to the effect for the given mesh.
  42148. * @param light The light containing the generator
  42149. * @param scene The scene the lights belongs to
  42150. * @param mesh The mesh we are binding the information to render
  42151. * @param lightIndex The light index in the effect used to render the mesh
  42152. * @param effect The effect we are binding the data to
  42153. */
  42154. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42155. if (light.shadowEnabled && mesh.receiveShadows) {
  42156. var shadowGenerator = light.getShadowGenerator();
  42157. if (shadowGenerator) {
  42158. shadowGenerator.bindShadowLight(lightIndex, effect);
  42159. }
  42160. }
  42161. };
  42162. /**
  42163. * Binds the light information to the effect.
  42164. * @param light The light containing the generator
  42165. * @param effect The effect we are binding the data to
  42166. * @param lightIndex The light index in the effect used to render
  42167. */
  42168. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42169. light.transferToEffect(effect, lightIndex + "");
  42170. };
  42171. /**
  42172. * Binds the lights information from the scene to the effect for the given mesh.
  42173. * @param scene The scene the lights belongs to
  42174. * @param mesh The mesh we are binding the information to render
  42175. * @param effect The effect we are binding the data to
  42176. * @param defines The generated defines for the effect
  42177. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42178. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42179. */
  42180. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42181. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42182. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42183. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42184. for (var i = 0; i < len; i++) {
  42185. var light = mesh._lightSources[i];
  42186. var iAsString = i.toString();
  42187. var scaledIntensity = light.getScaledIntensity();
  42188. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42189. MaterialHelper.BindLightProperties(light, effect, i);
  42190. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42191. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42192. if (defines["SPECULARTERM"]) {
  42193. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42194. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42195. }
  42196. // Shadows
  42197. if (scene.shadowsEnabled) {
  42198. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42199. }
  42200. light._uniformBuffer.update();
  42201. }
  42202. };
  42203. /**
  42204. * Binds the fog information from the scene to the effect for the given mesh.
  42205. * @param scene The scene the lights belongs to
  42206. * @param mesh The mesh we are binding the information to render
  42207. * @param effect The effect we are binding the data to
  42208. */
  42209. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42210. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42211. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42212. effect.setColor3("vFogColor", scene.fogColor);
  42213. }
  42214. };
  42215. /**
  42216. * Binds the bones information from the mesh to the effect.
  42217. * @param mesh The mesh we are binding the information to render
  42218. * @param effect The effect we are binding the data to
  42219. */
  42220. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42221. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42222. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42223. if (matrices && effect) {
  42224. effect.setMatrices("mBones", matrices);
  42225. }
  42226. }
  42227. };
  42228. /**
  42229. * Binds the morph targets information from the mesh to the effect.
  42230. * @param abstractMesh The mesh we are binding the information to render
  42231. * @param effect The effect we are binding the data to
  42232. */
  42233. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42234. var manager = abstractMesh.morphTargetManager;
  42235. if (!abstractMesh || !manager) {
  42236. return;
  42237. }
  42238. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42239. };
  42240. /**
  42241. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42242. * @param defines The generated defines used in the effect
  42243. * @param effect The effect we are binding the data to
  42244. * @param scene The scene we are willing to render with logarithmic scale for
  42245. */
  42246. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42247. if (defines["LOGARITHMICDEPTH"]) {
  42248. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42249. }
  42250. };
  42251. /**
  42252. * Binds the clip plane information from the scene to the effect.
  42253. * @param scene The scene the clip plane information are extracted from
  42254. * @param effect The effect we are binding the data to
  42255. */
  42256. MaterialHelper.BindClipPlane = function (effect, scene) {
  42257. if (scene.clipPlane) {
  42258. var clipPlane = scene.clipPlane;
  42259. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42260. }
  42261. };
  42262. return MaterialHelper;
  42263. }());
  42264. BABYLON.MaterialHelper = MaterialHelper;
  42265. })(BABYLON || (BABYLON = {}));
  42266. //# sourceMappingURL=babylon.materialHelper.js.map
  42267. var BABYLON;
  42268. (function (BABYLON) {
  42269. var PushMaterial = /** @class */ (function (_super) {
  42270. __extends(PushMaterial, _super);
  42271. function PushMaterial(name, scene) {
  42272. var _this = _super.call(this, name, scene) || this;
  42273. _this._normalMatrix = new BABYLON.Matrix();
  42274. _this.storeEffectOnSubMeshes = true;
  42275. return _this;
  42276. }
  42277. PushMaterial.prototype.getEffect = function () {
  42278. return this._activeEffect;
  42279. };
  42280. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42281. if (!mesh) {
  42282. return false;
  42283. }
  42284. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42285. return true;
  42286. }
  42287. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42288. };
  42289. /**
  42290. * Binds the given world matrix to the active effect
  42291. *
  42292. * @param world the matrix to bind
  42293. */
  42294. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42295. this._activeEffect.setMatrix("world", world);
  42296. };
  42297. /**
  42298. * Binds the given normal matrix to the active effect
  42299. *
  42300. * @param normalMatrix the matrix to bind
  42301. */
  42302. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42303. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42304. };
  42305. PushMaterial.prototype.bind = function (world, mesh) {
  42306. if (!mesh) {
  42307. return;
  42308. }
  42309. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42310. };
  42311. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42312. if (effect === void 0) { effect = null; }
  42313. _super.prototype._afterBind.call(this, mesh);
  42314. this.getScene()._cachedEffect = effect;
  42315. };
  42316. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42317. if (visibility === void 0) { visibility = 1; }
  42318. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42319. };
  42320. return PushMaterial;
  42321. }(BABYLON.Material));
  42322. BABYLON.PushMaterial = PushMaterial;
  42323. })(BABYLON || (BABYLON = {}));
  42324. //# sourceMappingURL=babylon.pushMaterial.js.map
  42325. var BABYLON;
  42326. (function (BABYLON) {
  42327. /** @ignore */
  42328. var StandardMaterialDefines = /** @class */ (function (_super) {
  42329. __extends(StandardMaterialDefines, _super);
  42330. function StandardMaterialDefines() {
  42331. var _this = _super.call(this) || this;
  42332. _this.MAINUV1 = false;
  42333. _this.MAINUV2 = false;
  42334. _this.DIFFUSE = false;
  42335. _this.DIFFUSEDIRECTUV = 0;
  42336. _this.AMBIENT = false;
  42337. _this.AMBIENTDIRECTUV = 0;
  42338. _this.OPACITY = false;
  42339. _this.OPACITYDIRECTUV = 0;
  42340. _this.OPACITYRGB = false;
  42341. _this.REFLECTION = false;
  42342. _this.EMISSIVE = false;
  42343. _this.EMISSIVEDIRECTUV = 0;
  42344. _this.SPECULAR = false;
  42345. _this.SPECULARDIRECTUV = 0;
  42346. _this.BUMP = false;
  42347. _this.BUMPDIRECTUV = 0;
  42348. _this.PARALLAX = false;
  42349. _this.PARALLAXOCCLUSION = false;
  42350. _this.SPECULAROVERALPHA = false;
  42351. _this.CLIPPLANE = false;
  42352. _this.ALPHATEST = false;
  42353. _this.DEPTHPREPASS = false;
  42354. _this.ALPHAFROMDIFFUSE = false;
  42355. _this.POINTSIZE = false;
  42356. _this.FOG = false;
  42357. _this.SPECULARTERM = false;
  42358. _this.DIFFUSEFRESNEL = false;
  42359. _this.OPACITYFRESNEL = false;
  42360. _this.REFLECTIONFRESNEL = false;
  42361. _this.REFRACTIONFRESNEL = false;
  42362. _this.EMISSIVEFRESNEL = false;
  42363. _this.FRESNEL = false;
  42364. _this.NORMAL = false;
  42365. _this.UV1 = false;
  42366. _this.UV2 = false;
  42367. _this.VERTEXCOLOR = false;
  42368. _this.VERTEXALPHA = false;
  42369. _this.NUM_BONE_INFLUENCERS = 0;
  42370. _this.BonesPerMesh = 0;
  42371. _this.INSTANCES = false;
  42372. _this.GLOSSINESS = false;
  42373. _this.ROUGHNESS = false;
  42374. _this.EMISSIVEASILLUMINATION = false;
  42375. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42376. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42377. _this.LIGHTMAP = false;
  42378. _this.LIGHTMAPDIRECTUV = 0;
  42379. _this.OBJECTSPACE_NORMALMAP = false;
  42380. _this.USELIGHTMAPASSHADOWMAP = false;
  42381. _this.REFLECTIONMAP_3D = false;
  42382. _this.REFLECTIONMAP_SPHERICAL = false;
  42383. _this.REFLECTIONMAP_PLANAR = false;
  42384. _this.REFLECTIONMAP_CUBIC = false;
  42385. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42386. _this.REFLECTIONMAP_PROJECTION = false;
  42387. _this.REFLECTIONMAP_SKYBOX = false;
  42388. _this.REFLECTIONMAP_EXPLICIT = false;
  42389. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42390. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42391. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42392. _this.INVERTCUBICMAP = false;
  42393. _this.LOGARITHMICDEPTH = false;
  42394. _this.REFRACTION = false;
  42395. _this.REFRACTIONMAP_3D = false;
  42396. _this.REFLECTIONOVERALPHA = false;
  42397. _this.TWOSIDEDLIGHTING = false;
  42398. _this.SHADOWFLOAT = false;
  42399. _this.MORPHTARGETS = false;
  42400. _this.MORPHTARGETS_NORMAL = false;
  42401. _this.MORPHTARGETS_TANGENT = false;
  42402. _this.NUM_MORPH_INFLUENCERS = 0;
  42403. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42404. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42405. _this.IMAGEPROCESSING = false;
  42406. _this.VIGNETTE = false;
  42407. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42408. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42409. _this.TONEMAPPING = false;
  42410. _this.CONTRAST = false;
  42411. _this.COLORCURVES = false;
  42412. _this.COLORGRADING = false;
  42413. _this.COLORGRADING3D = false;
  42414. _this.SAMPLER3DGREENDEPTH = false;
  42415. _this.SAMPLER3DBGRMAP = false;
  42416. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42417. /**
  42418. * If the reflection texture on this material is in linear color space
  42419. * @ignore
  42420. */
  42421. _this.IS_REFLECTION_LINEAR = false;
  42422. /**
  42423. * If the refraction texture on this material is in linear color space
  42424. * @ignore
  42425. */
  42426. _this.IS_REFRACTION_LINEAR = false;
  42427. _this.EXPOSURE = false;
  42428. _this.rebuild();
  42429. return _this;
  42430. }
  42431. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42432. var modes = [
  42433. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42434. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42435. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42436. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42437. ];
  42438. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42439. var mode = modes_1[_i];
  42440. this[mode] = (mode === modeToEnable);
  42441. }
  42442. };
  42443. return StandardMaterialDefines;
  42444. }(BABYLON.MaterialDefines));
  42445. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42446. var StandardMaterial = /** @class */ (function (_super) {
  42447. __extends(StandardMaterial, _super);
  42448. function StandardMaterial(name, scene) {
  42449. var _this = _super.call(this, name, scene) || this;
  42450. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42451. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42452. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42453. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42454. _this.specularPower = 64;
  42455. _this._useAlphaFromDiffuseTexture = false;
  42456. _this._useEmissiveAsIllumination = false;
  42457. _this._linkEmissiveWithDiffuse = false;
  42458. _this._useSpecularOverAlpha = false;
  42459. _this._useReflectionOverAlpha = false;
  42460. _this._disableLighting = false;
  42461. _this._useObjectSpaceNormalMap = false;
  42462. _this._useParallax = false;
  42463. _this._useParallaxOcclusion = false;
  42464. _this.parallaxScaleBias = 0.05;
  42465. _this._roughness = 0;
  42466. _this.indexOfRefraction = 0.98;
  42467. _this.invertRefractionY = true;
  42468. /**
  42469. * Defines the alpha limits in alpha test mode
  42470. */
  42471. _this.alphaCutOff = 0.4;
  42472. _this._useLightmapAsShadowmap = false;
  42473. _this._useReflectionFresnelFromSpecular = false;
  42474. _this._useGlossinessFromSpecularMapAlpha = false;
  42475. _this._maxSimultaneousLights = 4;
  42476. /**
  42477. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42478. */
  42479. _this._invertNormalMapX = false;
  42480. /**
  42481. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42482. */
  42483. _this._invertNormalMapY = false;
  42484. /**
  42485. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42486. */
  42487. _this._twoSidedLighting = false;
  42488. _this._renderTargets = new BABYLON.SmartArray(16);
  42489. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42490. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42491. // Setup the default processing configuration to the scene.
  42492. _this._attachImageProcessingConfiguration(null);
  42493. _this.getRenderTargetTextures = function () {
  42494. _this._renderTargets.reset();
  42495. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42496. _this._renderTargets.push(_this._reflectionTexture);
  42497. }
  42498. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42499. _this._renderTargets.push(_this._refractionTexture);
  42500. }
  42501. return _this._renderTargets;
  42502. };
  42503. return _this;
  42504. }
  42505. ;
  42506. ;
  42507. ;
  42508. ;
  42509. ;
  42510. ;
  42511. ;
  42512. ;
  42513. ;
  42514. ;
  42515. ;
  42516. ;
  42517. ;
  42518. ;
  42519. ;
  42520. ;
  42521. ;
  42522. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42523. /**
  42524. * Gets the image processing configuration used either in this material.
  42525. */
  42526. get: function () {
  42527. return this._imageProcessingConfiguration;
  42528. },
  42529. /**
  42530. * Sets the Default image processing configuration used either in the this material.
  42531. *
  42532. * If sets to null, the scene one is in use.
  42533. */
  42534. set: function (value) {
  42535. this._attachImageProcessingConfiguration(value);
  42536. // Ensure the effect will be rebuilt.
  42537. this._markAllSubMeshesAsTexturesDirty();
  42538. },
  42539. enumerable: true,
  42540. configurable: true
  42541. });
  42542. /**
  42543. * Attaches a new image processing configuration to the Standard Material.
  42544. * @param configuration
  42545. */
  42546. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42547. var _this = this;
  42548. if (configuration === this._imageProcessingConfiguration) {
  42549. return;
  42550. }
  42551. // Detaches observer.
  42552. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42553. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42554. }
  42555. // Pick the scene configuration if needed.
  42556. if (!configuration) {
  42557. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42558. }
  42559. else {
  42560. this._imageProcessingConfiguration = configuration;
  42561. }
  42562. // Attaches observer.
  42563. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42564. _this._markAllSubMeshesAsImageProcessingDirty();
  42565. });
  42566. };
  42567. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42568. /**
  42569. * Gets wether the color curves effect is enabled.
  42570. */
  42571. get: function () {
  42572. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42573. },
  42574. /**
  42575. * Sets wether the color curves effect is enabled.
  42576. */
  42577. set: function (value) {
  42578. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42579. },
  42580. enumerable: true,
  42581. configurable: true
  42582. });
  42583. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42584. /**
  42585. * Gets wether the color grading effect is enabled.
  42586. */
  42587. get: function () {
  42588. return this.imageProcessingConfiguration.colorGradingEnabled;
  42589. },
  42590. /**
  42591. * Gets wether the color grading effect is enabled.
  42592. */
  42593. set: function (value) {
  42594. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42595. },
  42596. enumerable: true,
  42597. configurable: true
  42598. });
  42599. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42600. /**
  42601. * Gets wether tonemapping is enabled or not.
  42602. */
  42603. get: function () {
  42604. return this._imageProcessingConfiguration.toneMappingEnabled;
  42605. },
  42606. /**
  42607. * Sets wether tonemapping is enabled or not
  42608. */
  42609. set: function (value) {
  42610. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42611. },
  42612. enumerable: true,
  42613. configurable: true
  42614. });
  42615. ;
  42616. ;
  42617. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42618. /**
  42619. * The camera exposure used on this material.
  42620. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42621. * This corresponds to a photographic exposure.
  42622. */
  42623. get: function () {
  42624. return this._imageProcessingConfiguration.exposure;
  42625. },
  42626. /**
  42627. * The camera exposure used on this material.
  42628. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42629. * This corresponds to a photographic exposure.
  42630. */
  42631. set: function (value) {
  42632. this._imageProcessingConfiguration.exposure = value;
  42633. },
  42634. enumerable: true,
  42635. configurable: true
  42636. });
  42637. ;
  42638. ;
  42639. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42640. /**
  42641. * Gets The camera contrast used on this material.
  42642. */
  42643. get: function () {
  42644. return this._imageProcessingConfiguration.contrast;
  42645. },
  42646. /**
  42647. * Sets The camera contrast used on this material.
  42648. */
  42649. set: function (value) {
  42650. this._imageProcessingConfiguration.contrast = value;
  42651. },
  42652. enumerable: true,
  42653. configurable: true
  42654. });
  42655. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42656. /**
  42657. * Gets the Color Grading 2D Lookup Texture.
  42658. */
  42659. get: function () {
  42660. return this._imageProcessingConfiguration.colorGradingTexture;
  42661. },
  42662. /**
  42663. * Sets the Color Grading 2D Lookup Texture.
  42664. */
  42665. set: function (value) {
  42666. this._imageProcessingConfiguration.colorGradingTexture = value;
  42667. },
  42668. enumerable: true,
  42669. configurable: true
  42670. });
  42671. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42672. /**
  42673. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42674. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42675. * 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;
  42676. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42677. */
  42678. get: function () {
  42679. return this._imageProcessingConfiguration.colorCurves;
  42680. },
  42681. /**
  42682. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42683. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42684. * 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;
  42685. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42686. */
  42687. set: function (value) {
  42688. this._imageProcessingConfiguration.colorCurves = value;
  42689. },
  42690. enumerable: true,
  42691. configurable: true
  42692. });
  42693. StandardMaterial.prototype.getClassName = function () {
  42694. return "StandardMaterial";
  42695. };
  42696. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42697. get: function () {
  42698. return this._useLogarithmicDepth;
  42699. },
  42700. set: function (value) {
  42701. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42702. this._markAllSubMeshesAsMiscDirty();
  42703. },
  42704. enumerable: true,
  42705. configurable: true
  42706. });
  42707. StandardMaterial.prototype.needAlphaBlending = function () {
  42708. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42709. };
  42710. StandardMaterial.prototype.needAlphaTesting = function () {
  42711. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42712. };
  42713. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42714. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42715. };
  42716. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42717. return this._diffuseTexture;
  42718. };
  42719. /**
  42720. * Child classes can use it to update shaders
  42721. */
  42722. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42723. if (useInstances === void 0) { useInstances = false; }
  42724. if (subMesh.effect && this.isFrozen) {
  42725. if (this._wasPreviouslyReady && subMesh.effect) {
  42726. return true;
  42727. }
  42728. }
  42729. if (!subMesh._materialDefines) {
  42730. subMesh._materialDefines = new StandardMaterialDefines();
  42731. }
  42732. var scene = this.getScene();
  42733. var defines = subMesh._materialDefines;
  42734. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42735. if (defines._renderId === scene.getRenderId()) {
  42736. return true;
  42737. }
  42738. }
  42739. var engine = scene.getEngine();
  42740. // Lights
  42741. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42742. // Textures
  42743. if (defines._areTexturesDirty) {
  42744. defines._needUVs = false;
  42745. defines.MAINUV1 = false;
  42746. defines.MAINUV2 = false;
  42747. if (scene.texturesEnabled) {
  42748. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42749. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42750. return false;
  42751. }
  42752. else {
  42753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42754. }
  42755. }
  42756. else {
  42757. defines.DIFFUSE = false;
  42758. }
  42759. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42760. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42761. return false;
  42762. }
  42763. else {
  42764. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42765. }
  42766. }
  42767. else {
  42768. defines.AMBIENT = false;
  42769. }
  42770. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42771. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42772. return false;
  42773. }
  42774. else {
  42775. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42776. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42777. }
  42778. }
  42779. else {
  42780. defines.OPACITY = false;
  42781. }
  42782. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42783. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42784. return false;
  42785. }
  42786. else {
  42787. defines._needNormals = true;
  42788. defines.REFLECTION = true;
  42789. defines.ROUGHNESS = (this._roughness > 0);
  42790. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42791. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42792. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42793. switch (this._reflectionTexture.coordinatesMode) {
  42794. case BABYLON.Texture.CUBIC_MODE:
  42795. case BABYLON.Texture.INVCUBIC_MODE:
  42796. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42797. break;
  42798. case BABYLON.Texture.EXPLICIT_MODE:
  42799. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42800. break;
  42801. case BABYLON.Texture.PLANAR_MODE:
  42802. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42803. break;
  42804. case BABYLON.Texture.PROJECTION_MODE:
  42805. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42806. break;
  42807. case BABYLON.Texture.SKYBOX_MODE:
  42808. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42809. break;
  42810. case BABYLON.Texture.SPHERICAL_MODE:
  42811. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42812. break;
  42813. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42814. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42815. break;
  42816. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42817. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42818. break;
  42819. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42820. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42821. break;
  42822. }
  42823. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42824. }
  42825. }
  42826. else {
  42827. defines.REFLECTION = false;
  42828. }
  42829. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42830. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42831. return false;
  42832. }
  42833. else {
  42834. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42835. }
  42836. }
  42837. else {
  42838. defines.EMISSIVE = false;
  42839. }
  42840. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42841. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42842. return false;
  42843. }
  42844. else {
  42845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42846. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42847. }
  42848. }
  42849. else {
  42850. defines.LIGHTMAP = false;
  42851. }
  42852. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42853. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42854. return false;
  42855. }
  42856. else {
  42857. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42858. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42859. }
  42860. }
  42861. else {
  42862. defines.SPECULAR = false;
  42863. }
  42864. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42865. // Bump texure can not be not blocking.
  42866. if (!this._bumpTexture.isReady()) {
  42867. return false;
  42868. }
  42869. else {
  42870. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42871. defines.PARALLAX = this._useParallax;
  42872. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42873. }
  42874. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42875. }
  42876. else {
  42877. defines.BUMP = false;
  42878. }
  42879. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42880. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42881. return false;
  42882. }
  42883. else {
  42884. defines._needUVs = true;
  42885. defines.REFRACTION = true;
  42886. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42887. }
  42888. }
  42889. else {
  42890. defines.REFRACTION = false;
  42891. }
  42892. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42893. }
  42894. else {
  42895. defines.DIFFUSE = false;
  42896. defines.AMBIENT = false;
  42897. defines.OPACITY = false;
  42898. defines.REFLECTION = false;
  42899. defines.EMISSIVE = false;
  42900. defines.LIGHTMAP = false;
  42901. defines.BUMP = false;
  42902. defines.REFRACTION = false;
  42903. }
  42904. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42905. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42906. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42907. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42908. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42909. }
  42910. if (defines._areImageProcessingDirty) {
  42911. if (!this._imageProcessingConfiguration.isReady()) {
  42912. return false;
  42913. }
  42914. this._imageProcessingConfiguration.prepareDefines(defines);
  42915. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42916. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42917. }
  42918. if (defines._areFresnelDirty) {
  42919. if (StandardMaterial.FresnelEnabled) {
  42920. // Fresnel
  42921. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42922. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42923. this._reflectionFresnelParameters) {
  42924. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42925. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42926. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42927. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42928. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42929. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42930. defines._needNormals = true;
  42931. defines.FRESNEL = true;
  42932. }
  42933. }
  42934. else {
  42935. defines.FRESNEL = false;
  42936. }
  42937. }
  42938. // Misc.
  42939. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42940. // Attribs
  42941. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42942. // Values that need to be evaluated on every frame
  42943. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42944. // Get correct effect
  42945. if (defines.isDirty) {
  42946. defines.markAsProcessed();
  42947. scene.resetCachedMaterial();
  42948. // Fallbacks
  42949. var fallbacks = new BABYLON.EffectFallbacks();
  42950. if (defines.REFLECTION) {
  42951. fallbacks.addFallback(0, "REFLECTION");
  42952. }
  42953. if (defines.SPECULAR) {
  42954. fallbacks.addFallback(0, "SPECULAR");
  42955. }
  42956. if (defines.BUMP) {
  42957. fallbacks.addFallback(0, "BUMP");
  42958. }
  42959. if (defines.PARALLAX) {
  42960. fallbacks.addFallback(1, "PARALLAX");
  42961. }
  42962. if (defines.PARALLAXOCCLUSION) {
  42963. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42964. }
  42965. if (defines.SPECULAROVERALPHA) {
  42966. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42967. }
  42968. if (defines.FOG) {
  42969. fallbacks.addFallback(1, "FOG");
  42970. }
  42971. if (defines.POINTSIZE) {
  42972. fallbacks.addFallback(0, "POINTSIZE");
  42973. }
  42974. if (defines.LOGARITHMICDEPTH) {
  42975. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42976. }
  42977. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42978. if (defines.SPECULARTERM) {
  42979. fallbacks.addFallback(0, "SPECULARTERM");
  42980. }
  42981. if (defines.DIFFUSEFRESNEL) {
  42982. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42983. }
  42984. if (defines.OPACITYFRESNEL) {
  42985. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42986. }
  42987. if (defines.REFLECTIONFRESNEL) {
  42988. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42989. }
  42990. if (defines.EMISSIVEFRESNEL) {
  42991. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42992. }
  42993. if (defines.FRESNEL) {
  42994. fallbacks.addFallback(4, "FRESNEL");
  42995. }
  42996. //Attributes
  42997. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42998. if (defines.NORMAL) {
  42999. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43000. }
  43001. if (defines.UV1) {
  43002. attribs.push(BABYLON.VertexBuffer.UVKind);
  43003. }
  43004. if (defines.UV2) {
  43005. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43006. }
  43007. if (defines.VERTEXCOLOR) {
  43008. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43009. }
  43010. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43011. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43012. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43013. var shaderName = "default";
  43014. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43015. "vFogInfos", "vFogColor", "pointSize",
  43016. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43017. "mBones",
  43018. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43019. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43020. "vReflectionPosition", "vReflectionSize",
  43021. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43022. ];
  43023. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43024. var uniformBuffers = ["Material", "Scene"];
  43025. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43026. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43027. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43028. uniformsNames: uniforms,
  43029. uniformBuffersNames: uniformBuffers,
  43030. samplers: samplers,
  43031. defines: defines,
  43032. maxSimultaneousLights: this._maxSimultaneousLights
  43033. });
  43034. if (this.customShaderNameResolve) {
  43035. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43036. }
  43037. var join = defines.toString();
  43038. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43039. attributes: attribs,
  43040. uniformsNames: uniforms,
  43041. uniformBuffersNames: uniformBuffers,
  43042. samplers: samplers,
  43043. defines: join,
  43044. fallbacks: fallbacks,
  43045. onCompiled: this.onCompiled,
  43046. onError: this.onError,
  43047. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43048. }, engine), defines);
  43049. this.buildUniformLayout();
  43050. }
  43051. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43052. return false;
  43053. }
  43054. defines._renderId = scene.getRenderId();
  43055. this._wasPreviouslyReady = true;
  43056. return true;
  43057. };
  43058. StandardMaterial.prototype.buildUniformLayout = function () {
  43059. // Order is important !
  43060. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43061. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43062. this._uniformBuffer.addUniform("opacityParts", 4);
  43063. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43064. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43065. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43066. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43067. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43068. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43069. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43070. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43071. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43072. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43073. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43074. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43075. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43076. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43077. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43078. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43079. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43080. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43081. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43082. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43083. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43084. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43085. this._uniformBuffer.addUniform("specularMatrix", 16);
  43086. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43087. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43088. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43089. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43090. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43091. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43092. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43093. this._uniformBuffer.addUniform("pointSize", 1);
  43094. this._uniformBuffer.create();
  43095. };
  43096. StandardMaterial.prototype.unbind = function () {
  43097. if (this._activeEffect) {
  43098. var needFlag = false;
  43099. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43100. this._activeEffect.setTexture("reflection2DSampler", null);
  43101. needFlag = true;
  43102. }
  43103. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43104. this._activeEffect.setTexture("refraction2DSampler", null);
  43105. needFlag = true;
  43106. }
  43107. if (needFlag) {
  43108. this._markAllSubMeshesAsTexturesDirty();
  43109. }
  43110. }
  43111. _super.prototype.unbind.call(this);
  43112. };
  43113. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43114. var scene = this.getScene();
  43115. var defines = subMesh._materialDefines;
  43116. if (!defines) {
  43117. return;
  43118. }
  43119. var effect = subMesh.effect;
  43120. if (!effect) {
  43121. return;
  43122. }
  43123. this._activeEffect = effect;
  43124. // Matrices
  43125. this.bindOnlyWorldMatrix(world);
  43126. // Normal Matrix
  43127. if (defines.OBJECTSPACE_NORMALMAP) {
  43128. world.toNormalMatrix(this._normalMatrix);
  43129. this.bindOnlyNormalMatrix(this._normalMatrix);
  43130. }
  43131. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43132. // Bones
  43133. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43134. if (mustRebind) {
  43135. this._uniformBuffer.bindToEffect(effect, "Material");
  43136. this.bindViewProjection(effect);
  43137. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43138. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43139. // Fresnel
  43140. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43141. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43142. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43143. }
  43144. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43145. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43146. }
  43147. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43148. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43149. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43150. }
  43151. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43152. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43153. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43154. }
  43155. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43156. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43157. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43158. }
  43159. }
  43160. // Textures
  43161. if (scene.texturesEnabled) {
  43162. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43163. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43164. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43165. if (this._diffuseTexture.hasAlpha) {
  43166. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43167. }
  43168. }
  43169. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43170. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43171. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43172. }
  43173. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43174. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43175. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43176. }
  43177. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43178. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43179. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43180. if (this._reflectionTexture.boundingBoxSize) {
  43181. var cubeTexture = this._reflectionTexture;
  43182. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43183. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43184. }
  43185. }
  43186. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43187. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43188. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43189. }
  43190. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43191. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43192. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43193. }
  43194. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43195. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43196. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43197. }
  43198. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43199. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43200. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43201. if (scene._mirroredCameraPosition) {
  43202. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43203. }
  43204. else {
  43205. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43206. }
  43207. }
  43208. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43209. var depth = 1.0;
  43210. if (!this._refractionTexture.isCube) {
  43211. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43212. if (this._refractionTexture.depth) {
  43213. depth = this._refractionTexture.depth;
  43214. }
  43215. }
  43216. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43217. }
  43218. }
  43219. // Point size
  43220. if (this.pointsCloud) {
  43221. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43222. }
  43223. if (defines.SPECULARTERM) {
  43224. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43225. }
  43226. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43227. // Diffuse
  43228. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43229. }
  43230. // Textures
  43231. if (scene.texturesEnabled) {
  43232. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43233. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43234. }
  43235. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43236. effect.setTexture("ambientSampler", this._ambientTexture);
  43237. }
  43238. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43239. effect.setTexture("opacitySampler", this._opacityTexture);
  43240. }
  43241. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43242. if (this._reflectionTexture.isCube) {
  43243. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43244. }
  43245. else {
  43246. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43247. }
  43248. }
  43249. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43250. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43251. }
  43252. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43253. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43254. }
  43255. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43256. effect.setTexture("specularSampler", this._specularTexture);
  43257. }
  43258. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43259. effect.setTexture("bumpSampler", this._bumpTexture);
  43260. }
  43261. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43262. var depth = 1.0;
  43263. if (this._refractionTexture.isCube) {
  43264. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43265. }
  43266. else {
  43267. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43268. }
  43269. }
  43270. }
  43271. // Clip plane
  43272. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43273. // Colors
  43274. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43275. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43276. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43277. }
  43278. if (mustRebind || !this.isFrozen) {
  43279. // Lights
  43280. if (scene.lightsEnabled && !this._disableLighting) {
  43281. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43282. }
  43283. // View
  43284. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43285. this.bindView(effect);
  43286. }
  43287. // Fog
  43288. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43289. // Morph targets
  43290. if (defines.NUM_MORPH_INFLUENCERS) {
  43291. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43292. }
  43293. // Log. depth
  43294. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43295. // image processing
  43296. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43297. this._imageProcessingConfiguration.bind(this._activeEffect);
  43298. }
  43299. }
  43300. this._uniformBuffer.update();
  43301. this._afterBind(mesh, this._activeEffect);
  43302. };
  43303. StandardMaterial.prototype.getAnimatables = function () {
  43304. var results = [];
  43305. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43306. results.push(this._diffuseTexture);
  43307. }
  43308. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43309. results.push(this._ambientTexture);
  43310. }
  43311. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43312. results.push(this._opacityTexture);
  43313. }
  43314. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43315. results.push(this._reflectionTexture);
  43316. }
  43317. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43318. results.push(this._emissiveTexture);
  43319. }
  43320. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43321. results.push(this._specularTexture);
  43322. }
  43323. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43324. results.push(this._bumpTexture);
  43325. }
  43326. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43327. results.push(this._lightmapTexture);
  43328. }
  43329. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43330. results.push(this._refractionTexture);
  43331. }
  43332. return results;
  43333. };
  43334. StandardMaterial.prototype.getActiveTextures = function () {
  43335. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43336. if (this._diffuseTexture) {
  43337. activeTextures.push(this._diffuseTexture);
  43338. }
  43339. if (this._ambientTexture) {
  43340. activeTextures.push(this._ambientTexture);
  43341. }
  43342. if (this._opacityTexture) {
  43343. activeTextures.push(this._opacityTexture);
  43344. }
  43345. if (this._reflectionTexture) {
  43346. activeTextures.push(this._reflectionTexture);
  43347. }
  43348. if (this._emissiveTexture) {
  43349. activeTextures.push(this._emissiveTexture);
  43350. }
  43351. if (this._specularTexture) {
  43352. activeTextures.push(this._specularTexture);
  43353. }
  43354. if (this._bumpTexture) {
  43355. activeTextures.push(this._bumpTexture);
  43356. }
  43357. if (this._lightmapTexture) {
  43358. activeTextures.push(this._lightmapTexture);
  43359. }
  43360. if (this._refractionTexture) {
  43361. activeTextures.push(this._refractionTexture);
  43362. }
  43363. return activeTextures;
  43364. };
  43365. StandardMaterial.prototype.hasTexture = function (texture) {
  43366. if (_super.prototype.hasTexture.call(this, texture)) {
  43367. return true;
  43368. }
  43369. if (this._diffuseTexture === texture) {
  43370. return true;
  43371. }
  43372. if (this._ambientTexture === texture) {
  43373. return true;
  43374. }
  43375. if (this._opacityTexture === texture) {
  43376. return true;
  43377. }
  43378. if (this._reflectionTexture === texture) {
  43379. return true;
  43380. }
  43381. if (this._emissiveTexture === texture) {
  43382. return true;
  43383. }
  43384. if (this._specularTexture === texture) {
  43385. return true;
  43386. }
  43387. if (this._bumpTexture === texture) {
  43388. return true;
  43389. }
  43390. if (this._lightmapTexture === texture) {
  43391. return true;
  43392. }
  43393. if (this._refractionTexture === texture) {
  43394. return true;
  43395. }
  43396. return false;
  43397. };
  43398. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43399. if (forceDisposeTextures) {
  43400. if (this._diffuseTexture) {
  43401. this._diffuseTexture.dispose();
  43402. }
  43403. if (this._ambientTexture) {
  43404. this._ambientTexture.dispose();
  43405. }
  43406. if (this._opacityTexture) {
  43407. this._opacityTexture.dispose();
  43408. }
  43409. if (this._reflectionTexture) {
  43410. this._reflectionTexture.dispose();
  43411. }
  43412. if (this._emissiveTexture) {
  43413. this._emissiveTexture.dispose();
  43414. }
  43415. if (this._specularTexture) {
  43416. this._specularTexture.dispose();
  43417. }
  43418. if (this._bumpTexture) {
  43419. this._bumpTexture.dispose();
  43420. }
  43421. if (this._lightmapTexture) {
  43422. this._lightmapTexture.dispose();
  43423. }
  43424. if (this._refractionTexture) {
  43425. this._refractionTexture.dispose();
  43426. }
  43427. }
  43428. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43429. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43430. }
  43431. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43432. };
  43433. StandardMaterial.prototype.clone = function (name) {
  43434. var _this = this;
  43435. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43436. result.name = name;
  43437. result.id = name;
  43438. return result;
  43439. };
  43440. StandardMaterial.prototype.serialize = function () {
  43441. return BABYLON.SerializationHelper.Serialize(this);
  43442. };
  43443. // Statics
  43444. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43445. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43446. };
  43447. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43448. get: function () {
  43449. return StandardMaterial._DiffuseTextureEnabled;
  43450. },
  43451. set: function (value) {
  43452. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43453. return;
  43454. }
  43455. StandardMaterial._DiffuseTextureEnabled = value;
  43456. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43457. },
  43458. enumerable: true,
  43459. configurable: true
  43460. });
  43461. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43462. get: function () {
  43463. return StandardMaterial._AmbientTextureEnabled;
  43464. },
  43465. set: function (value) {
  43466. if (StandardMaterial._AmbientTextureEnabled === value) {
  43467. return;
  43468. }
  43469. StandardMaterial._AmbientTextureEnabled = value;
  43470. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43471. },
  43472. enumerable: true,
  43473. configurable: true
  43474. });
  43475. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43476. get: function () {
  43477. return StandardMaterial._OpacityTextureEnabled;
  43478. },
  43479. set: function (value) {
  43480. if (StandardMaterial._OpacityTextureEnabled === value) {
  43481. return;
  43482. }
  43483. StandardMaterial._OpacityTextureEnabled = value;
  43484. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43485. },
  43486. enumerable: true,
  43487. configurable: true
  43488. });
  43489. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43490. get: function () {
  43491. return StandardMaterial._ReflectionTextureEnabled;
  43492. },
  43493. set: function (value) {
  43494. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43495. return;
  43496. }
  43497. StandardMaterial._ReflectionTextureEnabled = value;
  43498. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43499. },
  43500. enumerable: true,
  43501. configurable: true
  43502. });
  43503. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43504. get: function () {
  43505. return StandardMaterial._EmissiveTextureEnabled;
  43506. },
  43507. set: function (value) {
  43508. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43509. return;
  43510. }
  43511. StandardMaterial._EmissiveTextureEnabled = value;
  43512. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43513. },
  43514. enumerable: true,
  43515. configurable: true
  43516. });
  43517. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43518. get: function () {
  43519. return StandardMaterial._SpecularTextureEnabled;
  43520. },
  43521. set: function (value) {
  43522. if (StandardMaterial._SpecularTextureEnabled === value) {
  43523. return;
  43524. }
  43525. StandardMaterial._SpecularTextureEnabled = value;
  43526. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43527. },
  43528. enumerable: true,
  43529. configurable: true
  43530. });
  43531. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43532. get: function () {
  43533. return StandardMaterial._BumpTextureEnabled;
  43534. },
  43535. set: function (value) {
  43536. if (StandardMaterial._BumpTextureEnabled === value) {
  43537. return;
  43538. }
  43539. StandardMaterial._BumpTextureEnabled = value;
  43540. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43541. },
  43542. enumerable: true,
  43543. configurable: true
  43544. });
  43545. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43546. get: function () {
  43547. return StandardMaterial._LightmapTextureEnabled;
  43548. },
  43549. set: function (value) {
  43550. if (StandardMaterial._LightmapTextureEnabled === value) {
  43551. return;
  43552. }
  43553. StandardMaterial._LightmapTextureEnabled = value;
  43554. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43555. },
  43556. enumerable: true,
  43557. configurable: true
  43558. });
  43559. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43560. get: function () {
  43561. return StandardMaterial._RefractionTextureEnabled;
  43562. },
  43563. set: function (value) {
  43564. if (StandardMaterial._RefractionTextureEnabled === value) {
  43565. return;
  43566. }
  43567. StandardMaterial._RefractionTextureEnabled = value;
  43568. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43569. },
  43570. enumerable: true,
  43571. configurable: true
  43572. });
  43573. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43574. get: function () {
  43575. return StandardMaterial._ColorGradingTextureEnabled;
  43576. },
  43577. set: function (value) {
  43578. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43579. return;
  43580. }
  43581. StandardMaterial._ColorGradingTextureEnabled = value;
  43582. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43583. },
  43584. enumerable: true,
  43585. configurable: true
  43586. });
  43587. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43588. get: function () {
  43589. return StandardMaterial._FresnelEnabled;
  43590. },
  43591. set: function (value) {
  43592. if (StandardMaterial._FresnelEnabled === value) {
  43593. return;
  43594. }
  43595. StandardMaterial._FresnelEnabled = value;
  43596. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43597. },
  43598. enumerable: true,
  43599. configurable: true
  43600. });
  43601. // Flags used to enable or disable a type of texture for all Standard Materials
  43602. StandardMaterial._DiffuseTextureEnabled = true;
  43603. StandardMaterial._AmbientTextureEnabled = true;
  43604. StandardMaterial._OpacityTextureEnabled = true;
  43605. StandardMaterial._ReflectionTextureEnabled = true;
  43606. StandardMaterial._EmissiveTextureEnabled = true;
  43607. StandardMaterial._SpecularTextureEnabled = true;
  43608. StandardMaterial._BumpTextureEnabled = true;
  43609. StandardMaterial._LightmapTextureEnabled = true;
  43610. StandardMaterial._RefractionTextureEnabled = true;
  43611. StandardMaterial._ColorGradingTextureEnabled = true;
  43612. StandardMaterial._FresnelEnabled = true;
  43613. __decorate([
  43614. BABYLON.serializeAsTexture("diffuseTexture")
  43615. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43616. __decorate([
  43617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43618. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43619. __decorate([
  43620. BABYLON.serializeAsTexture("ambientTexture")
  43621. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43622. __decorate([
  43623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43624. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43625. __decorate([
  43626. BABYLON.serializeAsTexture("opacityTexture")
  43627. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43628. __decorate([
  43629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43630. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43631. __decorate([
  43632. BABYLON.serializeAsTexture("reflectionTexture")
  43633. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43634. __decorate([
  43635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43636. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43637. __decorate([
  43638. BABYLON.serializeAsTexture("emissiveTexture")
  43639. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43640. __decorate([
  43641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43642. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43643. __decorate([
  43644. BABYLON.serializeAsTexture("specularTexture")
  43645. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43646. __decorate([
  43647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43648. ], StandardMaterial.prototype, "specularTexture", void 0);
  43649. __decorate([
  43650. BABYLON.serializeAsTexture("bumpTexture")
  43651. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43652. __decorate([
  43653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43654. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43655. __decorate([
  43656. BABYLON.serializeAsTexture("lightmapTexture")
  43657. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43658. __decorate([
  43659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43660. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43661. __decorate([
  43662. BABYLON.serializeAsTexture("refractionTexture")
  43663. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43664. __decorate([
  43665. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43666. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43667. __decorate([
  43668. BABYLON.serializeAsColor3("ambient")
  43669. ], StandardMaterial.prototype, "ambientColor", void 0);
  43670. __decorate([
  43671. BABYLON.serializeAsColor3("diffuse")
  43672. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43673. __decorate([
  43674. BABYLON.serializeAsColor3("specular")
  43675. ], StandardMaterial.prototype, "specularColor", void 0);
  43676. __decorate([
  43677. BABYLON.serializeAsColor3("emissive")
  43678. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43679. __decorate([
  43680. BABYLON.serialize()
  43681. ], StandardMaterial.prototype, "specularPower", void 0);
  43682. __decorate([
  43683. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43684. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43685. __decorate([
  43686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43687. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43688. __decorate([
  43689. BABYLON.serialize("useEmissiveAsIllumination")
  43690. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43691. __decorate([
  43692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43693. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43694. __decorate([
  43695. BABYLON.serialize("linkEmissiveWithDiffuse")
  43696. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43697. __decorate([
  43698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43699. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43700. __decorate([
  43701. BABYLON.serialize("useSpecularOverAlpha")
  43702. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43703. __decorate([
  43704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43705. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43706. __decorate([
  43707. BABYLON.serialize("useReflectionOverAlpha")
  43708. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43709. __decorate([
  43710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43711. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43712. __decorate([
  43713. BABYLON.serialize("disableLighting")
  43714. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43715. __decorate([
  43716. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43717. ], StandardMaterial.prototype, "disableLighting", void 0);
  43718. __decorate([
  43719. BABYLON.serialize("useObjectSpaceNormalMap")
  43720. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43721. __decorate([
  43722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43723. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43724. __decorate([
  43725. BABYLON.serialize("useParallax")
  43726. ], StandardMaterial.prototype, "_useParallax", void 0);
  43727. __decorate([
  43728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43729. ], StandardMaterial.prototype, "useParallax", void 0);
  43730. __decorate([
  43731. BABYLON.serialize("useParallaxOcclusion")
  43732. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43733. __decorate([
  43734. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43735. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43736. __decorate([
  43737. BABYLON.serialize()
  43738. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43739. __decorate([
  43740. BABYLON.serialize("roughness")
  43741. ], StandardMaterial.prototype, "_roughness", void 0);
  43742. __decorate([
  43743. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43744. ], StandardMaterial.prototype, "roughness", void 0);
  43745. __decorate([
  43746. BABYLON.serialize()
  43747. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43748. __decorate([
  43749. BABYLON.serialize()
  43750. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43751. __decorate([
  43752. BABYLON.serialize()
  43753. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43754. __decorate([
  43755. BABYLON.serialize("useLightmapAsShadowmap")
  43756. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43757. __decorate([
  43758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43759. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43760. __decorate([
  43761. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43762. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43763. __decorate([
  43764. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43765. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43766. __decorate([
  43767. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43768. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43769. __decorate([
  43770. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43771. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43772. __decorate([
  43773. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43774. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43775. __decorate([
  43776. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43777. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43778. __decorate([
  43779. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43780. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43781. __decorate([
  43782. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43783. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43784. __decorate([
  43785. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43786. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43787. __decorate([
  43788. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43789. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43790. __decorate([
  43791. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43792. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43793. __decorate([
  43794. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43795. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43796. __decorate([
  43797. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43798. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43799. __decorate([
  43800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43801. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43802. __decorate([
  43803. BABYLON.serialize("maxSimultaneousLights")
  43804. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43805. __decorate([
  43806. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43807. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43808. __decorate([
  43809. BABYLON.serialize("invertNormalMapX")
  43810. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43811. __decorate([
  43812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43813. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43814. __decorate([
  43815. BABYLON.serialize("invertNormalMapY")
  43816. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43817. __decorate([
  43818. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43819. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43820. __decorate([
  43821. BABYLON.serialize("twoSidedLighting")
  43822. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43823. __decorate([
  43824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43825. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43826. __decorate([
  43827. BABYLON.serialize()
  43828. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43829. return StandardMaterial;
  43830. }(BABYLON.PushMaterial));
  43831. BABYLON.StandardMaterial = StandardMaterial;
  43832. })(BABYLON || (BABYLON = {}));
  43833. //# sourceMappingURL=babylon.standardMaterial.js.map
  43834. var BABYLON;
  43835. (function (BABYLON) {
  43836. /**
  43837. * Manages the defines for the PBR Material.
  43838. * @ignoreChildren
  43839. */
  43840. var PBRMaterialDefines = /** @class */ (function (_super) {
  43841. __extends(PBRMaterialDefines, _super);
  43842. /**
  43843. * Initializes the PBR Material defines.
  43844. */
  43845. function PBRMaterialDefines() {
  43846. var _this = _super.call(this) || this;
  43847. _this.PBR = true;
  43848. _this.MAINUV1 = false;
  43849. _this.MAINUV2 = false;
  43850. _this.UV1 = false;
  43851. _this.UV2 = false;
  43852. _this.ALBEDO = false;
  43853. _this.ALBEDODIRECTUV = 0;
  43854. _this.VERTEXCOLOR = false;
  43855. _this.AMBIENT = false;
  43856. _this.AMBIENTDIRECTUV = 0;
  43857. _this.AMBIENTINGRAYSCALE = false;
  43858. _this.OPACITY = false;
  43859. _this.VERTEXALPHA = false;
  43860. _this.OPACITYDIRECTUV = 0;
  43861. _this.OPACITYRGB = false;
  43862. _this.ALPHATEST = false;
  43863. _this.DEPTHPREPASS = false;
  43864. _this.ALPHABLEND = false;
  43865. _this.ALPHAFROMALBEDO = false;
  43866. _this.ALPHATESTVALUE = "0.5";
  43867. _this.SPECULAROVERALPHA = false;
  43868. _this.RADIANCEOVERALPHA = false;
  43869. _this.ALPHAFRESNEL = false;
  43870. _this.LINEARALPHAFRESNEL = false;
  43871. _this.PREMULTIPLYALPHA = false;
  43872. _this.EMISSIVE = false;
  43873. _this.EMISSIVEDIRECTUV = 0;
  43874. _this.REFLECTIVITY = false;
  43875. _this.REFLECTIVITYDIRECTUV = 0;
  43876. _this.SPECULARTERM = false;
  43877. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43878. _this.MICROSURFACEAUTOMATIC = false;
  43879. _this.LODBASEDMICROSFURACE = false;
  43880. _this.MICROSURFACEMAP = false;
  43881. _this.MICROSURFACEMAPDIRECTUV = 0;
  43882. _this.METALLICWORKFLOW = false;
  43883. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43884. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43885. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43886. _this.AOSTOREINMETALMAPRED = false;
  43887. _this.ENVIRONMENTBRDF = false;
  43888. _this.NORMAL = false;
  43889. _this.TANGENT = false;
  43890. _this.BUMP = false;
  43891. _this.BUMPDIRECTUV = 0;
  43892. _this.OBJECTSPACE_NORMALMAP = false;
  43893. _this.PARALLAX = false;
  43894. _this.PARALLAXOCCLUSION = false;
  43895. _this.NORMALXYSCALE = true;
  43896. _this.LIGHTMAP = false;
  43897. _this.LIGHTMAPDIRECTUV = 0;
  43898. _this.USELIGHTMAPASSHADOWMAP = false;
  43899. _this.GAMMALIGHTMAP = false;
  43900. _this.REFLECTION = false;
  43901. _this.REFLECTIONMAP_3D = false;
  43902. _this.REFLECTIONMAP_SPHERICAL = false;
  43903. _this.REFLECTIONMAP_PLANAR = false;
  43904. _this.REFLECTIONMAP_CUBIC = false;
  43905. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43906. _this.REFLECTIONMAP_PROJECTION = false;
  43907. _this.REFLECTIONMAP_SKYBOX = false;
  43908. _this.REFLECTIONMAP_EXPLICIT = false;
  43909. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43910. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43911. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43912. _this.INVERTCUBICMAP = false;
  43913. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43914. _this.USESPHERICALINVERTEX = false;
  43915. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43916. _this.LODINREFLECTIONALPHA = false;
  43917. _this.GAMMAREFLECTION = false;
  43918. _this.RADIANCEOCCLUSION = false;
  43919. _this.HORIZONOCCLUSION = false;
  43920. _this.REFRACTION = false;
  43921. _this.REFRACTIONMAP_3D = false;
  43922. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43923. _this.LODINREFRACTIONALPHA = false;
  43924. _this.GAMMAREFRACTION = false;
  43925. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43926. _this.INSTANCES = false;
  43927. _this.NUM_BONE_INFLUENCERS = 0;
  43928. _this.BonesPerMesh = 0;
  43929. _this.NONUNIFORMSCALING = false;
  43930. _this.MORPHTARGETS = false;
  43931. _this.MORPHTARGETS_NORMAL = false;
  43932. _this.MORPHTARGETS_TANGENT = false;
  43933. _this.NUM_MORPH_INFLUENCERS = 0;
  43934. _this.IMAGEPROCESSING = false;
  43935. _this.VIGNETTE = false;
  43936. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43937. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43938. _this.TONEMAPPING = false;
  43939. _this.CONTRAST = false;
  43940. _this.COLORCURVES = false;
  43941. _this.COLORGRADING = false;
  43942. _this.COLORGRADING3D = false;
  43943. _this.SAMPLER3DGREENDEPTH = false;
  43944. _this.SAMPLER3DBGRMAP = false;
  43945. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43946. _this.EXPOSURE = false;
  43947. _this.USEPHYSICALLIGHTFALLOFF = false;
  43948. _this.TWOSIDEDLIGHTING = false;
  43949. _this.SHADOWFLOAT = false;
  43950. _this.CLIPPLANE = false;
  43951. _this.POINTSIZE = false;
  43952. _this.FOG = false;
  43953. _this.LOGARITHMICDEPTH = false;
  43954. _this.FORCENORMALFORWARD = false;
  43955. _this.GEOMETRYAA = false;
  43956. _this.UNLIT = false;
  43957. _this.rebuild();
  43958. return _this;
  43959. }
  43960. /**
  43961. * Resets the PBR Material defines.
  43962. */
  43963. PBRMaterialDefines.prototype.reset = function () {
  43964. _super.prototype.reset.call(this);
  43965. this.ALPHATESTVALUE = "0.5";
  43966. this.PBR = true;
  43967. };
  43968. return PBRMaterialDefines;
  43969. }(BABYLON.MaterialDefines));
  43970. /**
  43971. * The Physically based material base class of BJS.
  43972. *
  43973. * This offers the main features of a standard PBR material.
  43974. * For more information, please refer to the documentation :
  43975. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43976. */
  43977. var PBRBaseMaterial = /** @class */ (function (_super) {
  43978. __extends(PBRBaseMaterial, _super);
  43979. /**
  43980. * Instantiates a new PBRMaterial instance.
  43981. *
  43982. * @param name The material name
  43983. * @param scene The scene the material will be use in.
  43984. */
  43985. function PBRBaseMaterial(name, scene) {
  43986. var _this = _super.call(this, name, scene) || this;
  43987. /**
  43988. * Intensity of the direct lights e.g. the four lights available in your scene.
  43989. * This impacts both the direct diffuse and specular highlights.
  43990. */
  43991. _this._directIntensity = 1.0;
  43992. /**
  43993. * Intensity of the emissive part of the material.
  43994. * This helps controlling the emissive effect without modifying the emissive color.
  43995. */
  43996. _this._emissiveIntensity = 1.0;
  43997. /**
  43998. * Intensity of the environment e.g. how much the environment will light the object
  43999. * either through harmonics for rough material or through the refelction for shiny ones.
  44000. */
  44001. _this._environmentIntensity = 1.0;
  44002. /**
  44003. * This is a special control allowing the reduction of the specular highlights coming from the
  44004. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44005. */
  44006. _this._specularIntensity = 1.0;
  44007. /**
  44008. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44009. */
  44010. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44011. /**
  44012. * Debug Control allowing disabling the bump map on this material.
  44013. */
  44014. _this._disableBumpMap = false;
  44015. /**
  44016. * AKA Occlusion Texture Intensity in other nomenclature.
  44017. */
  44018. _this._ambientTextureStrength = 1.0;
  44019. /**
  44020. * The color of a material in ambient lighting.
  44021. */
  44022. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44023. /**
  44024. * AKA Diffuse Color in other nomenclature.
  44025. */
  44026. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44027. /**
  44028. * AKA Specular Color in other nomenclature.
  44029. */
  44030. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44031. /**
  44032. * The color applied when light is reflected from a material.
  44033. */
  44034. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44035. /**
  44036. * The color applied when light is emitted from a material.
  44037. */
  44038. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44039. /**
  44040. * AKA Glossiness in other nomenclature.
  44041. */
  44042. _this._microSurface = 0.9;
  44043. /**
  44044. * source material index of refraction (IOR)' / 'destination material IOR.
  44045. */
  44046. _this._indexOfRefraction = 0.66;
  44047. /**
  44048. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44049. */
  44050. _this._invertRefractionY = false;
  44051. /**
  44052. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44053. * Materials half opaque for instance using refraction could benefit from this control.
  44054. */
  44055. _this._linkRefractionWithTransparency = false;
  44056. /**
  44057. * Specifies that the material will use the light map as a show map.
  44058. */
  44059. _this._useLightmapAsShadowmap = false;
  44060. /**
  44061. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44062. * makes the reflect vector face the model (under horizon).
  44063. */
  44064. _this._useHorizonOcclusion = true;
  44065. /**
  44066. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44067. * too much the area relying on ambient texture to define their ambient occlusion.
  44068. */
  44069. _this._useRadianceOcclusion = true;
  44070. /**
  44071. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44072. */
  44073. _this._useAlphaFromAlbedoTexture = false;
  44074. /**
  44075. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44076. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44077. */
  44078. _this._useSpecularOverAlpha = true;
  44079. /**
  44080. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44081. */
  44082. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44083. /**
  44084. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44085. */
  44086. _this._useRoughnessFromMetallicTextureAlpha = true;
  44087. /**
  44088. * Specifies if the metallic texture contains the roughness information in its green channel.
  44089. */
  44090. _this._useRoughnessFromMetallicTextureGreen = false;
  44091. /**
  44092. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44093. */
  44094. _this._useMetallnessFromMetallicTextureBlue = false;
  44095. /**
  44096. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44097. */
  44098. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44099. /**
  44100. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44101. */
  44102. _this._useAmbientInGrayScale = false;
  44103. /**
  44104. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44105. * The material will try to infer what glossiness each pixel should be.
  44106. */
  44107. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44108. /**
  44109. * BJS is using an harcoded light falloff based on a manually sets up range.
  44110. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44111. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44112. */
  44113. _this._usePhysicalLightFalloff = true;
  44114. /**
  44115. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44116. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44117. */
  44118. _this._useRadianceOverAlpha = true;
  44119. /**
  44120. * Allows using an object space normal map (instead of tangent space).
  44121. */
  44122. _this._useObjectSpaceNormalMap = false;
  44123. /**
  44124. * Allows using the bump map in parallax mode.
  44125. */
  44126. _this._useParallax = false;
  44127. /**
  44128. * Allows using the bump map in parallax occlusion mode.
  44129. */
  44130. _this._useParallaxOcclusion = false;
  44131. /**
  44132. * Controls the scale bias of the parallax mode.
  44133. */
  44134. _this._parallaxScaleBias = 0.05;
  44135. /**
  44136. * If sets to true, disables all the lights affecting the material.
  44137. */
  44138. _this._disableLighting = false;
  44139. /**
  44140. * Number of Simultaneous lights allowed on the material.
  44141. */
  44142. _this._maxSimultaneousLights = 4;
  44143. /**
  44144. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44145. */
  44146. _this._invertNormalMapX = false;
  44147. /**
  44148. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44149. */
  44150. _this._invertNormalMapY = false;
  44151. /**
  44152. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44153. */
  44154. _this._twoSidedLighting = false;
  44155. /**
  44156. * Defines the alpha limits in alpha test mode.
  44157. */
  44158. _this._alphaCutOff = 0.4;
  44159. /**
  44160. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44161. */
  44162. _this._forceAlphaTest = false;
  44163. /**
  44164. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44165. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44166. */
  44167. _this._useAlphaFresnel = false;
  44168. /**
  44169. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44170. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44171. */
  44172. _this._useLinearAlphaFresnel = false;
  44173. /**
  44174. * The transparency mode of the material.
  44175. */
  44176. _this._transparencyMode = null;
  44177. /**
  44178. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44179. * from cos thetav and roughness:
  44180. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44181. */
  44182. _this._environmentBRDFTexture = null;
  44183. /**
  44184. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44185. */
  44186. _this._forceIrradianceInFragment = false;
  44187. /**
  44188. * Force normal to face away from face.
  44189. */
  44190. _this._forceNormalForward = false;
  44191. /**
  44192. * Enables specular anti aliasing in the PBR shader.
  44193. * It will both interacts on the Geometry for analytical and IBL lighting.
  44194. * It also prefilter the roughness map based on the bump values.
  44195. */
  44196. _this._enableSpecularAntiAliasing = false;
  44197. /**
  44198. * Stores the available render targets.
  44199. */
  44200. _this._renderTargets = new BABYLON.SmartArray(16);
  44201. /**
  44202. * Sets the global ambient color for the material used in lighting calculations.
  44203. */
  44204. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44205. /**
  44206. * If set to true, no lighting calculations will be applied.
  44207. */
  44208. _this._unlit = false;
  44209. // Setup the default processing configuration to the scene.
  44210. _this._attachImageProcessingConfiguration(null);
  44211. _this.getRenderTargetTextures = function () {
  44212. _this._renderTargets.reset();
  44213. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44214. _this._renderTargets.push(_this._reflectionTexture);
  44215. }
  44216. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44217. _this._renderTargets.push(_this._refractionTexture);
  44218. }
  44219. return _this._renderTargets;
  44220. };
  44221. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44222. return _this;
  44223. }
  44224. /**
  44225. * Attaches a new image processing configuration to the PBR Material.
  44226. * @param configuration
  44227. */
  44228. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44229. var _this = this;
  44230. if (configuration === this._imageProcessingConfiguration) {
  44231. return;
  44232. }
  44233. // Detaches observer.
  44234. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44235. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44236. }
  44237. // Pick the scene configuration if needed.
  44238. if (!configuration) {
  44239. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44240. }
  44241. else {
  44242. this._imageProcessingConfiguration = configuration;
  44243. }
  44244. // Attaches observer.
  44245. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44246. _this._markAllSubMeshesAsImageProcessingDirty();
  44247. });
  44248. };
  44249. /**
  44250. * Gets the name of the material class.
  44251. */
  44252. PBRBaseMaterial.prototype.getClassName = function () {
  44253. return "PBRBaseMaterial";
  44254. };
  44255. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44256. /**
  44257. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44258. */
  44259. get: function () {
  44260. return this._useLogarithmicDepth;
  44261. },
  44262. /**
  44263. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44264. */
  44265. set: function (value) {
  44266. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44267. },
  44268. enumerable: true,
  44269. configurable: true
  44270. });
  44271. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44272. /**
  44273. * Gets the current transparency mode.
  44274. */
  44275. get: function () {
  44276. return this._transparencyMode;
  44277. },
  44278. /**
  44279. * Sets the transparency mode of the material.
  44280. */
  44281. set: function (value) {
  44282. if (this._transparencyMode === value) {
  44283. return;
  44284. }
  44285. this._transparencyMode = value;
  44286. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44287. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44288. },
  44289. enumerable: true,
  44290. configurable: true
  44291. });
  44292. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44293. /**
  44294. * Returns true if alpha blending should be disabled.
  44295. */
  44296. get: function () {
  44297. return (this._linkRefractionWithTransparency ||
  44298. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44299. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. /**
  44305. * Specifies whether or not this material should be rendered in alpha blend mode.
  44306. */
  44307. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44308. if (this._disableAlphaBlending) {
  44309. return false;
  44310. }
  44311. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44312. };
  44313. /**
  44314. * Specifies if the mesh will require alpha blending.
  44315. * @param mesh - BJS mesh.
  44316. */
  44317. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44318. if (this._disableAlphaBlending) {
  44319. return false;
  44320. }
  44321. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44322. };
  44323. /**
  44324. * Specifies whether or not this material should be rendered in alpha test mode.
  44325. */
  44326. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44327. if (this._forceAlphaTest) {
  44328. return true;
  44329. }
  44330. if (this._linkRefractionWithTransparency) {
  44331. return false;
  44332. }
  44333. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44334. };
  44335. /**
  44336. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44337. */
  44338. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44339. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44340. };
  44341. /**
  44342. * Gets the texture used for the alpha test.
  44343. */
  44344. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44345. return this._albedoTexture;
  44346. };
  44347. /**
  44348. * Specifies that the submesh is ready to be used.
  44349. * @param mesh - BJS mesh.
  44350. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44351. * @param useInstances - Specifies that instances should be used.
  44352. * @returns - boolean indicating that the submesh is ready or not.
  44353. */
  44354. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44355. if (subMesh.effect && this.isFrozen) {
  44356. if (this._wasPreviouslyReady) {
  44357. return true;
  44358. }
  44359. }
  44360. if (!subMesh._materialDefines) {
  44361. subMesh._materialDefines = new PBRMaterialDefines();
  44362. }
  44363. var defines = subMesh._materialDefines;
  44364. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44365. if (defines._renderId === this.getScene().getRenderId()) {
  44366. return true;
  44367. }
  44368. }
  44369. var scene = this.getScene();
  44370. var engine = scene.getEngine();
  44371. if (defines._areTexturesDirty) {
  44372. if (scene.texturesEnabled) {
  44373. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44374. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44375. return false;
  44376. }
  44377. }
  44378. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44379. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44380. return false;
  44381. }
  44382. }
  44383. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44384. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44385. return false;
  44386. }
  44387. }
  44388. var reflectionTexture = this._getReflectionTexture();
  44389. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44390. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44391. return false;
  44392. }
  44393. }
  44394. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44395. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44396. return false;
  44397. }
  44398. }
  44399. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44400. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44401. return false;
  44402. }
  44403. }
  44404. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44405. if (this._metallicTexture) {
  44406. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44407. return false;
  44408. }
  44409. }
  44410. else if (this._reflectivityTexture) {
  44411. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44412. return false;
  44413. }
  44414. }
  44415. if (this._microSurfaceTexture) {
  44416. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44417. return false;
  44418. }
  44419. }
  44420. }
  44421. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44422. // Bump texture cannot be not blocking.
  44423. if (!this._bumpTexture.isReady()) {
  44424. return false;
  44425. }
  44426. }
  44427. var refractionTexture = this._getRefractionTexture();
  44428. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44429. if (!refractionTexture.isReadyOrNotBlocking()) {
  44430. return false;
  44431. }
  44432. }
  44433. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44434. // This is blocking.
  44435. if (!this._environmentBRDFTexture.isReady()) {
  44436. return false;
  44437. }
  44438. }
  44439. }
  44440. }
  44441. if (defines._areImageProcessingDirty) {
  44442. if (!this._imageProcessingConfiguration.isReady()) {
  44443. return false;
  44444. }
  44445. }
  44446. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44447. mesh.createNormals(true);
  44448. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44449. }
  44450. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44451. if (effect) {
  44452. scene.resetCachedMaterial();
  44453. subMesh.setEffect(effect, defines);
  44454. this.buildUniformLayout();
  44455. }
  44456. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44457. return false;
  44458. }
  44459. defines._renderId = scene.getRenderId();
  44460. this._wasPreviouslyReady = true;
  44461. return true;
  44462. };
  44463. /**
  44464. * Specifies if the material uses metallic roughness workflow.
  44465. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44466. */
  44467. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44468. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44469. return true;
  44470. }
  44471. return false;
  44472. };
  44473. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44474. if (onCompiled === void 0) { onCompiled = null; }
  44475. if (onError === void 0) { onError = null; }
  44476. if (useInstances === void 0) { useInstances = null; }
  44477. if (useClipPlane === void 0) { useClipPlane = null; }
  44478. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44479. if (!defines.isDirty) {
  44480. return null;
  44481. }
  44482. defines.markAsProcessed();
  44483. var scene = this.getScene();
  44484. var engine = scene.getEngine();
  44485. // Fallbacks
  44486. var fallbacks = new BABYLON.EffectFallbacks();
  44487. var fallbackRank = 0;
  44488. if (defines.USESPHERICALINVERTEX) {
  44489. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44490. }
  44491. if (defines.FOG) {
  44492. fallbacks.addFallback(fallbackRank, "FOG");
  44493. }
  44494. if (defines.POINTSIZE) {
  44495. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44496. }
  44497. if (defines.LOGARITHMICDEPTH) {
  44498. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44499. }
  44500. if (defines.PARALLAX) {
  44501. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44502. }
  44503. if (defines.PARALLAXOCCLUSION) {
  44504. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44505. }
  44506. if (defines.ENVIRONMENTBRDF) {
  44507. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44508. }
  44509. if (defines.TANGENT) {
  44510. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44511. }
  44512. if (defines.BUMP) {
  44513. fallbacks.addFallback(fallbackRank++, "BUMP");
  44514. }
  44515. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44516. if (defines.SPECULARTERM) {
  44517. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44518. }
  44519. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44520. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44521. }
  44522. if (defines.LIGHTMAP) {
  44523. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44524. }
  44525. if (defines.NORMAL) {
  44526. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44527. }
  44528. if (defines.AMBIENT) {
  44529. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44530. }
  44531. if (defines.EMISSIVE) {
  44532. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44533. }
  44534. if (defines.VERTEXCOLOR) {
  44535. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44536. }
  44537. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44538. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44539. }
  44540. if (defines.MORPHTARGETS) {
  44541. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44542. }
  44543. //Attributes
  44544. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44545. if (defines.NORMAL) {
  44546. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44547. }
  44548. if (defines.TANGENT) {
  44549. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44550. }
  44551. if (defines.UV1) {
  44552. attribs.push(BABYLON.VertexBuffer.UVKind);
  44553. }
  44554. if (defines.UV2) {
  44555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44556. }
  44557. if (defines.VERTEXCOLOR) {
  44558. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44559. }
  44560. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44561. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44562. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44563. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44564. "vFogInfos", "vFogColor", "pointSize",
  44565. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44566. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44567. "mBones",
  44568. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44569. "vLightingIntensity",
  44570. "logarithmicDepthConstant",
  44571. "vSphericalX", "vSphericalY", "vSphericalZ",
  44572. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44573. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44574. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44575. "vTangentSpaceParams"
  44576. ];
  44577. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44578. "bumpSampler", "lightmapSampler", "opacitySampler",
  44579. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44580. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44581. "microSurfaceSampler", "environmentBrdfSampler"];
  44582. var uniformBuffers = ["Material", "Scene"];
  44583. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44584. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44585. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44586. uniformsNames: uniforms,
  44587. uniformBuffersNames: uniformBuffers,
  44588. samplers: samplers,
  44589. defines: defines,
  44590. maxSimultaneousLights: this._maxSimultaneousLights
  44591. });
  44592. var join = defines.toString();
  44593. return engine.createEffect("pbr", {
  44594. attributes: attribs,
  44595. uniformsNames: uniforms,
  44596. uniformBuffersNames: uniformBuffers,
  44597. samplers: samplers,
  44598. defines: join,
  44599. fallbacks: fallbacks,
  44600. onCompiled: onCompiled,
  44601. onError: onError,
  44602. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44603. }, engine);
  44604. };
  44605. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44606. if (useInstances === void 0) { useInstances = null; }
  44607. if (useClipPlane === void 0) { useClipPlane = null; }
  44608. var scene = this.getScene();
  44609. var engine = scene.getEngine();
  44610. // Lights
  44611. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44612. defines._needNormals = true;
  44613. // Textures
  44614. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44615. if (defines._areTexturesDirty) {
  44616. defines._needUVs = false;
  44617. if (scene.texturesEnabled) {
  44618. if (scene.getEngine().getCaps().textureLOD) {
  44619. defines.LODBASEDMICROSFURACE = true;
  44620. }
  44621. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44622. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44623. }
  44624. else {
  44625. defines.ALBEDO = false;
  44626. }
  44627. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44628. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44629. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44630. }
  44631. else {
  44632. defines.AMBIENT = false;
  44633. }
  44634. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44635. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44636. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44637. }
  44638. else {
  44639. defines.OPACITY = false;
  44640. }
  44641. var reflectionTexture = this._getReflectionTexture();
  44642. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44643. defines.REFLECTION = true;
  44644. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44645. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44646. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44647. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44648. defines.INVERTCUBICMAP = true;
  44649. }
  44650. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44651. switch (reflectionTexture.coordinatesMode) {
  44652. case BABYLON.Texture.CUBIC_MODE:
  44653. case BABYLON.Texture.INVCUBIC_MODE:
  44654. defines.REFLECTIONMAP_CUBIC = true;
  44655. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44656. break;
  44657. case BABYLON.Texture.EXPLICIT_MODE:
  44658. defines.REFLECTIONMAP_EXPLICIT = true;
  44659. break;
  44660. case BABYLON.Texture.PLANAR_MODE:
  44661. defines.REFLECTIONMAP_PLANAR = true;
  44662. break;
  44663. case BABYLON.Texture.PROJECTION_MODE:
  44664. defines.REFLECTIONMAP_PROJECTION = true;
  44665. break;
  44666. case BABYLON.Texture.SKYBOX_MODE:
  44667. defines.REFLECTIONMAP_SKYBOX = true;
  44668. break;
  44669. case BABYLON.Texture.SPHERICAL_MODE:
  44670. defines.REFLECTIONMAP_SPHERICAL = true;
  44671. break;
  44672. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44673. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44674. break;
  44675. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44676. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44677. break;
  44678. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44679. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44680. break;
  44681. }
  44682. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44683. if (reflectionTexture.sphericalPolynomial) {
  44684. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44685. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44686. defines.USESPHERICALINVERTEX = false;
  44687. }
  44688. else {
  44689. defines.USESPHERICALINVERTEX = true;
  44690. }
  44691. }
  44692. }
  44693. }
  44694. else {
  44695. defines.REFLECTION = false;
  44696. defines.REFLECTIONMAP_3D = false;
  44697. defines.REFLECTIONMAP_SPHERICAL = false;
  44698. defines.REFLECTIONMAP_PLANAR = false;
  44699. defines.REFLECTIONMAP_CUBIC = false;
  44700. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44701. defines.REFLECTIONMAP_PROJECTION = false;
  44702. defines.REFLECTIONMAP_SKYBOX = false;
  44703. defines.REFLECTIONMAP_EXPLICIT = false;
  44704. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44705. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44706. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44707. defines.INVERTCUBICMAP = false;
  44708. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44709. defines.USESPHERICALINVERTEX = false;
  44710. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44711. defines.LODINREFLECTIONALPHA = false;
  44712. defines.GAMMAREFLECTION = false;
  44713. }
  44714. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44715. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44716. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44717. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44718. }
  44719. else {
  44720. defines.LIGHTMAP = false;
  44721. }
  44722. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44723. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44724. }
  44725. else {
  44726. defines.EMISSIVE = false;
  44727. }
  44728. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44729. if (this._metallicTexture) {
  44730. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44731. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44732. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44733. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44734. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44735. }
  44736. else if (this._reflectivityTexture) {
  44737. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44738. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44739. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44740. }
  44741. else {
  44742. defines.REFLECTIVITY = false;
  44743. }
  44744. if (this._microSurfaceTexture) {
  44745. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44746. }
  44747. else {
  44748. defines.MICROSURFACEMAP = false;
  44749. }
  44750. }
  44751. else {
  44752. defines.REFLECTIVITY = false;
  44753. defines.MICROSURFACEMAP = false;
  44754. }
  44755. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44756. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44757. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44758. defines.PARALLAX = true;
  44759. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44760. }
  44761. else {
  44762. defines.PARALLAX = false;
  44763. }
  44764. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44765. }
  44766. else {
  44767. defines.BUMP = false;
  44768. }
  44769. var refractionTexture = this._getRefractionTexture();
  44770. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44771. defines.REFRACTION = true;
  44772. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44773. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44774. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44775. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44776. if (this._linkRefractionWithTransparency) {
  44777. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44778. }
  44779. }
  44780. else {
  44781. defines.REFRACTION = false;
  44782. }
  44783. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44784. defines.ENVIRONMENTBRDF = true;
  44785. }
  44786. else {
  44787. defines.ENVIRONMENTBRDF = false;
  44788. }
  44789. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44790. defines.ALPHAFROMALBEDO = true;
  44791. }
  44792. else {
  44793. defines.ALPHAFROMALBEDO = false;
  44794. }
  44795. }
  44796. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44797. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44798. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44799. if (!this.backFaceCulling && this._twoSidedLighting) {
  44800. defines.TWOSIDEDLIGHTING = true;
  44801. }
  44802. else {
  44803. defines.TWOSIDEDLIGHTING = false;
  44804. }
  44805. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44806. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44807. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44808. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44809. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44810. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44811. }
  44812. if (defines._areImageProcessingDirty) {
  44813. this._imageProcessingConfiguration.prepareDefines(defines);
  44814. }
  44815. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44816. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44817. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44818. // Misc.
  44819. if (defines._areMiscDirty) {
  44820. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44821. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44822. }
  44823. // Values that need to be evaluated on every frame
  44824. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44825. // Attribs
  44826. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44827. };
  44828. /**
  44829. * Force shader compilation
  44830. */
  44831. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44832. var _this = this;
  44833. var localOptions = __assign({ clipPlane: false }, options);
  44834. var defines = new PBRMaterialDefines();
  44835. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44836. if (effect.isReady()) {
  44837. if (onCompiled) {
  44838. onCompiled(this);
  44839. }
  44840. }
  44841. else {
  44842. effect.onCompileObservable.add(function () {
  44843. if (onCompiled) {
  44844. onCompiled(_this);
  44845. }
  44846. });
  44847. }
  44848. };
  44849. /**
  44850. * Initializes the uniform buffer layout for the shader.
  44851. */
  44852. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44853. // Order is important !
  44854. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44855. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44856. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44857. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44858. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44859. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44860. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44861. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44862. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44863. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44864. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44865. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44866. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44867. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44868. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44869. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44870. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44871. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44872. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44873. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44874. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44875. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44876. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44877. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44878. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44879. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44880. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44881. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44882. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44883. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44884. this._uniformBuffer.addUniform("pointSize", 1);
  44885. this._uniformBuffer.create();
  44886. };
  44887. /**
  44888. * Unbinds the textures.
  44889. */
  44890. PBRBaseMaterial.prototype.unbind = function () {
  44891. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44892. this._uniformBuffer.setTexture("reflectionSampler", null);
  44893. }
  44894. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44895. this._uniformBuffer.setTexture("refractionSampler", null);
  44896. }
  44897. _super.prototype.unbind.call(this);
  44898. };
  44899. /**
  44900. * Binds the submesh data.
  44901. * @param world - The world matrix.
  44902. * @param mesh - The BJS mesh.
  44903. * @param subMesh - A submesh of the BJS mesh.
  44904. */
  44905. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44906. var scene = this.getScene();
  44907. var defines = subMesh._materialDefines;
  44908. if (!defines) {
  44909. return;
  44910. }
  44911. var effect = subMesh.effect;
  44912. if (!effect) {
  44913. return;
  44914. }
  44915. this._activeEffect = effect;
  44916. // Matrices
  44917. this.bindOnlyWorldMatrix(world);
  44918. // Normal Matrix
  44919. if (defines.OBJECTSPACE_NORMALMAP) {
  44920. world.toNormalMatrix(this._normalMatrix);
  44921. this.bindOnlyNormalMatrix(this._normalMatrix);
  44922. }
  44923. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44924. // Bones
  44925. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44926. var reflectionTexture = null;
  44927. if (mustRebind) {
  44928. this._uniformBuffer.bindToEffect(effect, "Material");
  44929. this.bindViewProjection(effect);
  44930. reflectionTexture = this._getReflectionTexture();
  44931. var refractionTexture = this._getRefractionTexture();
  44932. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44933. // Texture uniforms
  44934. if (scene.texturesEnabled) {
  44935. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44936. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44937. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44938. }
  44939. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44940. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44941. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44942. }
  44943. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44944. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44945. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44946. }
  44947. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44948. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44949. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44950. if (reflectionTexture.boundingBoxSize) {
  44951. var cubeTexture = reflectionTexture;
  44952. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44953. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44954. }
  44955. var polynomials = reflectionTexture.sphericalPolynomial;
  44956. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44957. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44958. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44959. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44960. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44961. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44962. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44963. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44964. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44965. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44966. }
  44967. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44968. }
  44969. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44970. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44971. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44972. }
  44973. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44974. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44975. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44976. }
  44977. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44978. if (this._metallicTexture) {
  44979. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44980. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44981. }
  44982. else if (this._reflectivityTexture) {
  44983. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44984. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44985. }
  44986. if (this._microSurfaceTexture) {
  44987. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44988. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44989. }
  44990. }
  44991. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44992. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44993. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44994. if (scene._mirroredCameraPosition) {
  44995. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44996. }
  44997. else {
  44998. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44999. }
  45000. }
  45001. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45002. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45003. var depth = 1.0;
  45004. if (!refractionTexture.isCube) {
  45005. if (refractionTexture.depth) {
  45006. depth = refractionTexture.depth;
  45007. }
  45008. }
  45009. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45010. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45011. }
  45012. }
  45013. // Point size
  45014. if (this.pointsCloud) {
  45015. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45016. }
  45017. // Colors
  45018. if (defines.METALLICWORKFLOW) {
  45019. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45020. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45021. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45022. }
  45023. else {
  45024. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45025. }
  45026. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45027. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45028. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45029. // Misc
  45030. this._lightingInfos.x = this._directIntensity;
  45031. this._lightingInfos.y = this._emissiveIntensity;
  45032. this._lightingInfos.z = this._environmentIntensity;
  45033. this._lightingInfos.w = this._specularIntensity;
  45034. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45035. }
  45036. // Textures
  45037. if (scene.texturesEnabled) {
  45038. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45039. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45040. }
  45041. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45042. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45043. }
  45044. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45045. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45046. }
  45047. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45048. if (defines.LODBASEDMICROSFURACE) {
  45049. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45050. }
  45051. else {
  45052. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45053. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45054. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45055. }
  45056. }
  45057. if (defines.ENVIRONMENTBRDF) {
  45058. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45059. }
  45060. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45061. if (defines.LODBASEDMICROSFURACE) {
  45062. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45063. }
  45064. else {
  45065. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45066. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45067. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45068. }
  45069. }
  45070. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45071. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45072. }
  45073. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45074. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45075. }
  45076. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45077. if (this._metallicTexture) {
  45078. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45079. }
  45080. else if (this._reflectivityTexture) {
  45081. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45082. }
  45083. if (this._microSurfaceTexture) {
  45084. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45085. }
  45086. }
  45087. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45088. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45089. }
  45090. }
  45091. // Clip plane
  45092. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45093. // Colors
  45094. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45095. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45096. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45097. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45098. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45099. }
  45100. if (mustRebind || !this.isFrozen) {
  45101. // Lights
  45102. if (scene.lightsEnabled && !this._disableLighting) {
  45103. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45104. }
  45105. // View
  45106. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45107. this.bindView(effect);
  45108. }
  45109. // Fog
  45110. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45111. // Morph targets
  45112. if (defines.NUM_MORPH_INFLUENCERS) {
  45113. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45114. }
  45115. // image processing
  45116. this._imageProcessingConfiguration.bind(this._activeEffect);
  45117. // Log. depth
  45118. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45119. }
  45120. this._uniformBuffer.update();
  45121. this._afterBind(mesh);
  45122. };
  45123. /**
  45124. * Returns the animatable textures.
  45125. * @returns - Array of animatable textures.
  45126. */
  45127. PBRBaseMaterial.prototype.getAnimatables = function () {
  45128. var results = [];
  45129. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45130. results.push(this._albedoTexture);
  45131. }
  45132. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45133. results.push(this._ambientTexture);
  45134. }
  45135. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45136. results.push(this._opacityTexture);
  45137. }
  45138. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45139. results.push(this._reflectionTexture);
  45140. }
  45141. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45142. results.push(this._emissiveTexture);
  45143. }
  45144. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45145. results.push(this._metallicTexture);
  45146. }
  45147. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45148. results.push(this._reflectivityTexture);
  45149. }
  45150. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45151. results.push(this._bumpTexture);
  45152. }
  45153. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45154. results.push(this._lightmapTexture);
  45155. }
  45156. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45157. results.push(this._refractionTexture);
  45158. }
  45159. return results;
  45160. };
  45161. /**
  45162. * Returns the texture used for reflections.
  45163. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45164. */
  45165. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45166. if (this._reflectionTexture) {
  45167. return this._reflectionTexture;
  45168. }
  45169. return this.getScene().environmentTexture;
  45170. };
  45171. /**
  45172. * Returns the texture used for refraction or null if none is used.
  45173. * @returns - Refection texture if present. If no refraction texture and refraction
  45174. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45175. */
  45176. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45177. if (this._refractionTexture) {
  45178. return this._refractionTexture;
  45179. }
  45180. if (this._linkRefractionWithTransparency) {
  45181. return this.getScene().environmentTexture;
  45182. }
  45183. return null;
  45184. };
  45185. /**
  45186. * Disposes the resources of the material.
  45187. * @param forceDisposeEffect - Forces the disposal of effects.
  45188. * @param forceDisposeTextures - Forces the disposal of all textures.
  45189. */
  45190. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45191. if (forceDisposeTextures) {
  45192. if (this._albedoTexture) {
  45193. this._albedoTexture.dispose();
  45194. }
  45195. if (this._ambientTexture) {
  45196. this._ambientTexture.dispose();
  45197. }
  45198. if (this._opacityTexture) {
  45199. this._opacityTexture.dispose();
  45200. }
  45201. if (this._reflectionTexture) {
  45202. this._reflectionTexture.dispose();
  45203. }
  45204. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45205. this._environmentBRDFTexture.dispose();
  45206. }
  45207. if (this._emissiveTexture) {
  45208. this._emissiveTexture.dispose();
  45209. }
  45210. if (this._metallicTexture) {
  45211. this._metallicTexture.dispose();
  45212. }
  45213. if (this._reflectivityTexture) {
  45214. this._reflectivityTexture.dispose();
  45215. }
  45216. if (this._bumpTexture) {
  45217. this._bumpTexture.dispose();
  45218. }
  45219. if (this._lightmapTexture) {
  45220. this._lightmapTexture.dispose();
  45221. }
  45222. if (this._refractionTexture) {
  45223. this._refractionTexture.dispose();
  45224. }
  45225. }
  45226. this._renderTargets.dispose();
  45227. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45228. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45229. }
  45230. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45231. };
  45232. /**
  45233. * Stores the reflectivity values based on metallic roughness workflow.
  45234. */
  45235. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45236. __decorate([
  45237. BABYLON.serializeAsImageProcessingConfiguration()
  45238. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45239. __decorate([
  45240. BABYLON.serialize()
  45241. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45242. __decorate([
  45243. BABYLON.serialize()
  45244. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45245. return PBRBaseMaterial;
  45246. }(BABYLON.PushMaterial));
  45247. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45248. })(BABYLON || (BABYLON = {}));
  45249. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45250. var BABYLON;
  45251. (function (BABYLON) {
  45252. /**
  45253. * The Physically based simple base material of BJS.
  45254. *
  45255. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45256. * It is used as the base class for both the specGloss and metalRough conventions.
  45257. */
  45258. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45259. __extends(PBRBaseSimpleMaterial, _super);
  45260. /**
  45261. * Instantiates a new PBRMaterial instance.
  45262. *
  45263. * @param name The material name
  45264. * @param scene The scene the material will be use in.
  45265. */
  45266. function PBRBaseSimpleMaterial(name, scene) {
  45267. var _this = _super.call(this, name, scene) || this;
  45268. /**
  45269. * Number of Simultaneous lights allowed on the material.
  45270. */
  45271. _this.maxSimultaneousLights = 4;
  45272. /**
  45273. * If sets to true, disables all the lights affecting the material.
  45274. */
  45275. _this.disableLighting = false;
  45276. /**
  45277. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45278. */
  45279. _this.invertNormalMapX = false;
  45280. /**
  45281. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45282. */
  45283. _this.invertNormalMapY = false;
  45284. /**
  45285. * Emissivie color used to self-illuminate the model.
  45286. */
  45287. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45288. /**
  45289. * Occlusion Channel Strenght.
  45290. */
  45291. _this.occlusionStrength = 1.0;
  45292. _this.useLightmapAsShadowmap = false;
  45293. _this._useAlphaFromAlbedoTexture = true;
  45294. _this._useAmbientInGrayScale = true;
  45295. return _this;
  45296. }
  45297. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45298. /**
  45299. * Gets the current double sided mode.
  45300. */
  45301. get: function () {
  45302. return this._twoSidedLighting;
  45303. },
  45304. /**
  45305. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45306. */
  45307. set: function (value) {
  45308. if (this._twoSidedLighting === value) {
  45309. return;
  45310. }
  45311. this._twoSidedLighting = value;
  45312. this.backFaceCulling = !value;
  45313. this._markAllSubMeshesAsTexturesDirty();
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. /**
  45319. * Return the active textures of the material.
  45320. */
  45321. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45322. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45323. if (this.environmentTexture) {
  45324. activeTextures.push(this.environmentTexture);
  45325. }
  45326. if (this.normalTexture) {
  45327. activeTextures.push(this.normalTexture);
  45328. }
  45329. if (this.emissiveTexture) {
  45330. activeTextures.push(this.emissiveTexture);
  45331. }
  45332. if (this.occlusionTexture) {
  45333. activeTextures.push(this.occlusionTexture);
  45334. }
  45335. if (this.lightmapTexture) {
  45336. activeTextures.push(this.lightmapTexture);
  45337. }
  45338. return activeTextures;
  45339. };
  45340. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45341. if (_super.prototype.hasTexture.call(this, texture)) {
  45342. return true;
  45343. }
  45344. if (this.lightmapTexture === texture) {
  45345. return true;
  45346. }
  45347. return false;
  45348. };
  45349. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45350. return "PBRBaseSimpleMaterial";
  45351. };
  45352. __decorate([
  45353. BABYLON.serialize(),
  45354. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45355. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45356. __decorate([
  45357. BABYLON.serialize(),
  45358. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45359. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45360. __decorate([
  45361. BABYLON.serializeAsTexture(),
  45362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45363. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45364. __decorate([
  45365. BABYLON.serialize(),
  45366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45367. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45368. __decorate([
  45369. BABYLON.serialize(),
  45370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45371. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45372. __decorate([
  45373. BABYLON.serializeAsTexture(),
  45374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45375. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45376. __decorate([
  45377. BABYLON.serializeAsColor3("emissive"),
  45378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45379. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45380. __decorate([
  45381. BABYLON.serializeAsTexture(),
  45382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45383. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45384. __decorate([
  45385. BABYLON.serialize(),
  45386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45387. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45388. __decorate([
  45389. BABYLON.serializeAsTexture(),
  45390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45391. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45392. __decorate([
  45393. BABYLON.serialize(),
  45394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45395. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45396. __decorate([
  45397. BABYLON.serialize()
  45398. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45399. __decorate([
  45400. BABYLON.serializeAsTexture(),
  45401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45402. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45403. __decorate([
  45404. BABYLON.serialize(),
  45405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45406. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45407. return PBRBaseSimpleMaterial;
  45408. }(BABYLON.PBRBaseMaterial));
  45409. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45410. })(BABYLON || (BABYLON = {}));
  45411. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45412. var BABYLON;
  45413. (function (BABYLON) {
  45414. /**
  45415. * The Physically based material of BJS.
  45416. *
  45417. * This offers the main features of a standard PBR material.
  45418. * For more information, please refer to the documentation :
  45419. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45420. */
  45421. var PBRMaterial = /** @class */ (function (_super) {
  45422. __extends(PBRMaterial, _super);
  45423. /**
  45424. * Instantiates a new PBRMaterial instance.
  45425. *
  45426. * @param name The material name
  45427. * @param scene The scene the material will be use in.
  45428. */
  45429. function PBRMaterial(name, scene) {
  45430. var _this = _super.call(this, name, scene) || this;
  45431. /**
  45432. * Intensity of the direct lights e.g. the four lights available in your scene.
  45433. * This impacts both the direct diffuse and specular highlights.
  45434. */
  45435. _this.directIntensity = 1.0;
  45436. /**
  45437. * Intensity of the emissive part of the material.
  45438. * This helps controlling the emissive effect without modifying the emissive color.
  45439. */
  45440. _this.emissiveIntensity = 1.0;
  45441. /**
  45442. * Intensity of the environment e.g. how much the environment will light the object
  45443. * either through harmonics for rough material or through the refelction for shiny ones.
  45444. */
  45445. _this.environmentIntensity = 1.0;
  45446. /**
  45447. * This is a special control allowing the reduction of the specular highlights coming from the
  45448. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45449. */
  45450. _this.specularIntensity = 1.0;
  45451. /**
  45452. * Debug Control allowing disabling the bump map on this material.
  45453. */
  45454. _this.disableBumpMap = false;
  45455. /**
  45456. * AKA Occlusion Texture Intensity in other nomenclature.
  45457. */
  45458. _this.ambientTextureStrength = 1.0;
  45459. /**
  45460. * The color of a material in ambient lighting.
  45461. */
  45462. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45463. /**
  45464. * AKA Diffuse Color in other nomenclature.
  45465. */
  45466. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45467. /**
  45468. * AKA Specular Color in other nomenclature.
  45469. */
  45470. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45471. /**
  45472. * The color reflected from the material.
  45473. */
  45474. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45475. /**
  45476. * The color emitted from the material.
  45477. */
  45478. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45479. /**
  45480. * AKA Glossiness in other nomenclature.
  45481. */
  45482. _this.microSurface = 1.0;
  45483. /**
  45484. * source material index of refraction (IOR)' / 'destination material IOR.
  45485. */
  45486. _this.indexOfRefraction = 0.66;
  45487. /**
  45488. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45489. */
  45490. _this.invertRefractionY = false;
  45491. /**
  45492. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45493. * Materials half opaque for instance using refraction could benefit from this control.
  45494. */
  45495. _this.linkRefractionWithTransparency = false;
  45496. _this.useLightmapAsShadowmap = false;
  45497. /**
  45498. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45499. */
  45500. _this.useAlphaFromAlbedoTexture = false;
  45501. /**
  45502. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45503. */
  45504. _this.forceAlphaTest = false;
  45505. /**
  45506. * Defines the alpha limits in alpha test mode.
  45507. */
  45508. _this.alphaCutOff = 0.4;
  45509. /**
  45510. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45511. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45512. */
  45513. _this.useSpecularOverAlpha = true;
  45514. /**
  45515. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45516. */
  45517. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45518. /**
  45519. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45520. */
  45521. _this.useRoughnessFromMetallicTextureAlpha = true;
  45522. /**
  45523. * Specifies if the metallic texture contains the roughness information in its green channel.
  45524. */
  45525. _this.useRoughnessFromMetallicTextureGreen = false;
  45526. /**
  45527. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45528. */
  45529. _this.useMetallnessFromMetallicTextureBlue = false;
  45530. /**
  45531. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45532. */
  45533. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45534. /**
  45535. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45536. */
  45537. _this.useAmbientInGrayScale = false;
  45538. /**
  45539. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45540. * The material will try to infer what glossiness each pixel should be.
  45541. */
  45542. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45543. /**
  45544. * BJS is using an harcoded light falloff based on a manually sets up range.
  45545. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45546. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45547. */
  45548. _this.usePhysicalLightFalloff = true;
  45549. /**
  45550. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45551. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45552. */
  45553. _this.useRadianceOverAlpha = true;
  45554. /**
  45555. * Allows using an object space normal map (instead of tangent space).
  45556. */
  45557. _this.useObjectSpaceNormalMap = false;
  45558. /**
  45559. * Allows using the bump map in parallax mode.
  45560. */
  45561. _this.useParallax = false;
  45562. /**
  45563. * Allows using the bump map in parallax occlusion mode.
  45564. */
  45565. _this.useParallaxOcclusion = false;
  45566. /**
  45567. * Controls the scale bias of the parallax mode.
  45568. */
  45569. _this.parallaxScaleBias = 0.05;
  45570. /**
  45571. * If sets to true, disables all the lights affecting the material.
  45572. */
  45573. _this.disableLighting = false;
  45574. /**
  45575. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45576. */
  45577. _this.forceIrradianceInFragment = false;
  45578. /**
  45579. * Number of Simultaneous lights allowed on the material.
  45580. */
  45581. _this.maxSimultaneousLights = 4;
  45582. /**
  45583. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45584. */
  45585. _this.invertNormalMapX = false;
  45586. /**
  45587. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45588. */
  45589. _this.invertNormalMapY = false;
  45590. /**
  45591. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45592. */
  45593. _this.twoSidedLighting = false;
  45594. /**
  45595. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45596. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45597. */
  45598. _this.useAlphaFresnel = false;
  45599. /**
  45600. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45601. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45602. */
  45603. _this.useLinearAlphaFresnel = false;
  45604. /**
  45605. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45606. * And/Or occlude the blended part.
  45607. */
  45608. _this.environmentBRDFTexture = null;
  45609. /**
  45610. * Force normal to face away from face.
  45611. */
  45612. _this.forceNormalForward = false;
  45613. /**
  45614. * Enables specular anti aliasing in the PBR shader.
  45615. * It will both interacts on the Geometry for analytical and IBL lighting.
  45616. * It also prefilter the roughness map based on the bump values.
  45617. */
  45618. _this.enableSpecularAntiAliasing = false;
  45619. /**
  45620. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45621. * makes the reflect vector face the model (under horizon).
  45622. */
  45623. _this.useHorizonOcclusion = true;
  45624. /**
  45625. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45626. * too much the area relying on ambient texture to define their ambient occlusion.
  45627. */
  45628. _this.useRadianceOcclusion = true;
  45629. /**
  45630. * If set to true, no lighting calculations will be applied.
  45631. */
  45632. _this.unlit = false;
  45633. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45634. return _this;
  45635. }
  45636. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45637. /**
  45638. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45639. */
  45640. get: function () {
  45641. return this._PBRMATERIAL_OPAQUE;
  45642. },
  45643. enumerable: true,
  45644. configurable: true
  45645. });
  45646. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45647. /**
  45648. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45649. */
  45650. get: function () {
  45651. return this._PBRMATERIAL_ALPHATEST;
  45652. },
  45653. enumerable: true,
  45654. configurable: true
  45655. });
  45656. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45657. /**
  45658. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45659. */
  45660. get: function () {
  45661. return this._PBRMATERIAL_ALPHABLEND;
  45662. },
  45663. enumerable: true,
  45664. configurable: true
  45665. });
  45666. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45667. /**
  45668. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45669. * They are also discarded below the alpha cutoff threshold to improve performances.
  45670. */
  45671. get: function () {
  45672. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45673. },
  45674. enumerable: true,
  45675. configurable: true
  45676. });
  45677. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45678. /**
  45679. * Gets the image processing configuration used either in this material.
  45680. */
  45681. get: function () {
  45682. return this._imageProcessingConfiguration;
  45683. },
  45684. /**
  45685. * Sets the Default image processing configuration used either in the this material.
  45686. *
  45687. * If sets to null, the scene one is in use.
  45688. */
  45689. set: function (value) {
  45690. this._attachImageProcessingConfiguration(value);
  45691. // Ensure the effect will be rebuilt.
  45692. this._markAllSubMeshesAsTexturesDirty();
  45693. },
  45694. enumerable: true,
  45695. configurable: true
  45696. });
  45697. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45698. /**
  45699. * Gets wether the color curves effect is enabled.
  45700. */
  45701. get: function () {
  45702. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45703. },
  45704. /**
  45705. * Sets wether the color curves effect is enabled.
  45706. */
  45707. set: function (value) {
  45708. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45709. },
  45710. enumerable: true,
  45711. configurable: true
  45712. });
  45713. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45714. /**
  45715. * Gets wether the color grading effect is enabled.
  45716. */
  45717. get: function () {
  45718. return this.imageProcessingConfiguration.colorGradingEnabled;
  45719. },
  45720. /**
  45721. * Gets wether the color grading effect is enabled.
  45722. */
  45723. set: function (value) {
  45724. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45725. },
  45726. enumerable: true,
  45727. configurable: true
  45728. });
  45729. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45730. /**
  45731. * Gets wether tonemapping is enabled or not.
  45732. */
  45733. get: function () {
  45734. return this._imageProcessingConfiguration.toneMappingEnabled;
  45735. },
  45736. /**
  45737. * Sets wether tonemapping is enabled or not
  45738. */
  45739. set: function (value) {
  45740. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45741. },
  45742. enumerable: true,
  45743. configurable: true
  45744. });
  45745. ;
  45746. ;
  45747. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45748. /**
  45749. * The camera exposure used on this material.
  45750. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45751. * This corresponds to a photographic exposure.
  45752. */
  45753. get: function () {
  45754. return this._imageProcessingConfiguration.exposure;
  45755. },
  45756. /**
  45757. * The camera exposure used on this material.
  45758. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45759. * This corresponds to a photographic exposure.
  45760. */
  45761. set: function (value) {
  45762. this._imageProcessingConfiguration.exposure = value;
  45763. },
  45764. enumerable: true,
  45765. configurable: true
  45766. });
  45767. ;
  45768. ;
  45769. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45770. /**
  45771. * Gets The camera contrast used on this material.
  45772. */
  45773. get: function () {
  45774. return this._imageProcessingConfiguration.contrast;
  45775. },
  45776. /**
  45777. * Sets The camera contrast used on this material.
  45778. */
  45779. set: function (value) {
  45780. this._imageProcessingConfiguration.contrast = value;
  45781. },
  45782. enumerable: true,
  45783. configurable: true
  45784. });
  45785. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45786. /**
  45787. * Gets the Color Grading 2D Lookup Texture.
  45788. */
  45789. get: function () {
  45790. return this._imageProcessingConfiguration.colorGradingTexture;
  45791. },
  45792. /**
  45793. * Sets the Color Grading 2D Lookup Texture.
  45794. */
  45795. set: function (value) {
  45796. this._imageProcessingConfiguration.colorGradingTexture = value;
  45797. },
  45798. enumerable: true,
  45799. configurable: true
  45800. });
  45801. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45802. /**
  45803. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45804. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45805. * 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;
  45806. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45807. */
  45808. get: function () {
  45809. return this._imageProcessingConfiguration.colorCurves;
  45810. },
  45811. /**
  45812. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45813. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45814. * 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;
  45815. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45816. */
  45817. set: function (value) {
  45818. this._imageProcessingConfiguration.colorCurves = value;
  45819. },
  45820. enumerable: true,
  45821. configurable: true
  45822. });
  45823. /**
  45824. * Returns the name of this material class.
  45825. */
  45826. PBRMaterial.prototype.getClassName = function () {
  45827. return "PBRMaterial";
  45828. };
  45829. /**
  45830. * Returns an array of the actively used textures.
  45831. * @returns - Array of BaseTextures
  45832. */
  45833. PBRMaterial.prototype.getActiveTextures = function () {
  45834. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45835. if (this._albedoTexture) {
  45836. activeTextures.push(this._albedoTexture);
  45837. }
  45838. if (this._ambientTexture) {
  45839. activeTextures.push(this._ambientTexture);
  45840. }
  45841. if (this._opacityTexture) {
  45842. activeTextures.push(this._opacityTexture);
  45843. }
  45844. if (this._reflectionTexture) {
  45845. activeTextures.push(this._reflectionTexture);
  45846. }
  45847. if (this._emissiveTexture) {
  45848. activeTextures.push(this._emissiveTexture);
  45849. }
  45850. if (this._reflectivityTexture) {
  45851. activeTextures.push(this._reflectivityTexture);
  45852. }
  45853. if (this._metallicTexture) {
  45854. activeTextures.push(this._metallicTexture);
  45855. }
  45856. if (this._microSurfaceTexture) {
  45857. activeTextures.push(this._microSurfaceTexture);
  45858. }
  45859. if (this._bumpTexture) {
  45860. activeTextures.push(this._bumpTexture);
  45861. }
  45862. if (this._lightmapTexture) {
  45863. activeTextures.push(this._lightmapTexture);
  45864. }
  45865. if (this._refractionTexture) {
  45866. activeTextures.push(this._refractionTexture);
  45867. }
  45868. return activeTextures;
  45869. };
  45870. /**
  45871. * Checks to see if a texture is used in the material.
  45872. * @param texture - Base texture to use.
  45873. * @returns - Boolean specifying if a texture is used in the material.
  45874. */
  45875. PBRMaterial.prototype.hasTexture = function (texture) {
  45876. if (_super.prototype.hasTexture.call(this, texture)) {
  45877. return true;
  45878. }
  45879. if (this._albedoTexture === texture) {
  45880. return true;
  45881. }
  45882. if (this._ambientTexture === texture) {
  45883. return true;
  45884. }
  45885. if (this._opacityTexture === texture) {
  45886. return true;
  45887. }
  45888. if (this._reflectionTexture === texture) {
  45889. return true;
  45890. }
  45891. if (this._reflectivityTexture === texture) {
  45892. return true;
  45893. }
  45894. if (this._metallicTexture === texture) {
  45895. return true;
  45896. }
  45897. if (this._microSurfaceTexture === texture) {
  45898. return true;
  45899. }
  45900. if (this._bumpTexture === texture) {
  45901. return true;
  45902. }
  45903. if (this._lightmapTexture === texture) {
  45904. return true;
  45905. }
  45906. if (this._refractionTexture === texture) {
  45907. return true;
  45908. }
  45909. return false;
  45910. };
  45911. /**
  45912. * Makes a duplicate of the current material.
  45913. * @param name - name to use for the new material.
  45914. */
  45915. PBRMaterial.prototype.clone = function (name) {
  45916. var _this = this;
  45917. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45918. clone.id = name;
  45919. clone.name = name;
  45920. return clone;
  45921. };
  45922. /**
  45923. * Serializes this PBR Material.
  45924. * @returns - An object with the serialized material.
  45925. */
  45926. PBRMaterial.prototype.serialize = function () {
  45927. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45928. serializationObject.customType = "BABYLON.PBRMaterial";
  45929. return serializationObject;
  45930. };
  45931. // Statics
  45932. /**
  45933. * Parses a PBR Material from a serialized object.
  45934. * @param source - Serialized object.
  45935. * @param scene - BJS scene instance.
  45936. * @param rootUrl - url for the scene object
  45937. * @returns - PBRMaterial
  45938. */
  45939. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45940. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45941. };
  45942. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45943. /**
  45944. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45945. */
  45946. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45947. /**
  45948. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45949. */
  45950. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45951. /**
  45952. * 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.
  45953. * They are also discarded below the alpha cutoff threshold to improve performances.
  45954. */
  45955. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45956. __decorate([
  45957. BABYLON.serialize(),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45959. ], PBRMaterial.prototype, "directIntensity", void 0);
  45960. __decorate([
  45961. BABYLON.serialize(),
  45962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45963. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45964. __decorate([
  45965. BABYLON.serialize(),
  45966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45967. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45968. __decorate([
  45969. BABYLON.serialize(),
  45970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45971. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45972. __decorate([
  45973. BABYLON.serialize(),
  45974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45975. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45976. __decorate([
  45977. BABYLON.serializeAsTexture(),
  45978. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45979. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45980. __decorate([
  45981. BABYLON.serializeAsTexture(),
  45982. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45983. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45984. __decorate([
  45985. BABYLON.serialize(),
  45986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45987. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45988. __decorate([
  45989. BABYLON.serializeAsTexture(),
  45990. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45991. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45992. __decorate([
  45993. BABYLON.serializeAsTexture(),
  45994. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45995. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45996. __decorate([
  45997. BABYLON.serializeAsTexture(),
  45998. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45999. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46000. __decorate([
  46001. BABYLON.serializeAsTexture(),
  46002. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46003. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46004. __decorate([
  46005. BABYLON.serializeAsTexture(),
  46006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46007. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46008. __decorate([
  46009. BABYLON.serialize(),
  46010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46011. ], PBRMaterial.prototype, "metallic", void 0);
  46012. __decorate([
  46013. BABYLON.serialize(),
  46014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46015. ], PBRMaterial.prototype, "roughness", void 0);
  46016. __decorate([
  46017. BABYLON.serializeAsTexture(),
  46018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46019. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46020. __decorate([
  46021. BABYLON.serializeAsTexture(),
  46022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46023. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46024. __decorate([
  46025. BABYLON.serializeAsTexture(),
  46026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46027. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46028. __decorate([
  46029. BABYLON.serializeAsTexture(),
  46030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46031. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46032. __decorate([
  46033. BABYLON.serializeAsColor3("ambient"),
  46034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46035. ], PBRMaterial.prototype, "ambientColor", void 0);
  46036. __decorate([
  46037. BABYLON.serializeAsColor3("albedo"),
  46038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46039. ], PBRMaterial.prototype, "albedoColor", void 0);
  46040. __decorate([
  46041. BABYLON.serializeAsColor3("reflectivity"),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46043. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46044. __decorate([
  46045. BABYLON.serializeAsColor3("reflection"),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46047. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46048. __decorate([
  46049. BABYLON.serializeAsColor3("emissive"),
  46050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46051. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46052. __decorate([
  46053. BABYLON.serialize(),
  46054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46055. ], PBRMaterial.prototype, "microSurface", void 0);
  46056. __decorate([
  46057. BABYLON.serialize(),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46059. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46060. __decorate([
  46061. BABYLON.serialize(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46063. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46064. __decorate([
  46065. BABYLON.serialize(),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46067. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46068. __decorate([
  46069. BABYLON.serialize(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46071. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46072. __decorate([
  46073. BABYLON.serialize(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46075. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46076. __decorate([
  46077. BABYLON.serialize(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46079. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46080. __decorate([
  46081. BABYLON.serialize(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46083. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46087. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46088. __decorate([
  46089. BABYLON.serialize(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46091. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46092. __decorate([
  46093. BABYLON.serialize(),
  46094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46095. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46096. __decorate([
  46097. BABYLON.serialize(),
  46098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46099. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46100. __decorate([
  46101. BABYLON.serialize(),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46103. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46104. __decorate([
  46105. BABYLON.serialize(),
  46106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46107. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46108. __decorate([
  46109. BABYLON.serialize(),
  46110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46111. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46112. __decorate([
  46113. BABYLON.serialize(),
  46114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46115. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46116. __decorate([
  46117. BABYLON.serialize(),
  46118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46119. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46120. __decorate([
  46121. BABYLON.serialize(),
  46122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46123. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46124. __decorate([
  46125. BABYLON.serialize(),
  46126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46127. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46128. __decorate([
  46129. BABYLON.serialize(),
  46130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46131. ], PBRMaterial.prototype, "useParallax", void 0);
  46132. __decorate([
  46133. BABYLON.serialize(),
  46134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46135. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46136. __decorate([
  46137. BABYLON.serialize(),
  46138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46139. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46140. __decorate([
  46141. BABYLON.serialize(),
  46142. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46143. ], PBRMaterial.prototype, "disableLighting", void 0);
  46144. __decorate([
  46145. BABYLON.serialize(),
  46146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46147. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46148. __decorate([
  46149. BABYLON.serialize(),
  46150. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46151. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46152. __decorate([
  46153. BABYLON.serialize(),
  46154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46155. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46156. __decorate([
  46157. BABYLON.serialize(),
  46158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46159. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46160. __decorate([
  46161. BABYLON.serialize(),
  46162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46163. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46164. __decorate([
  46165. BABYLON.serialize(),
  46166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46167. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46168. __decorate([
  46169. BABYLON.serialize(),
  46170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46171. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46172. __decorate([
  46173. BABYLON.serializeAsTexture(),
  46174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46175. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46176. __decorate([
  46177. BABYLON.serialize(),
  46178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46179. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46180. __decorate([
  46181. BABYLON.serialize(),
  46182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46183. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46184. __decorate([
  46185. BABYLON.serialize(),
  46186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46187. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46188. __decorate([
  46189. BABYLON.serialize(),
  46190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46191. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46192. __decorate([
  46193. BABYLON.serialize(),
  46194. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46195. ], PBRMaterial.prototype, "unlit", void 0);
  46196. return PBRMaterial;
  46197. }(BABYLON.PBRBaseMaterial));
  46198. BABYLON.PBRMaterial = PBRMaterial;
  46199. })(BABYLON || (BABYLON = {}));
  46200. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46201. var BABYLON;
  46202. (function (BABYLON) {
  46203. /**
  46204. * The PBR material of BJS following the metal roughness convention.
  46205. *
  46206. * This fits to the PBR convention in the GLTF definition:
  46207. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46208. */
  46209. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46210. __extends(PBRMetallicRoughnessMaterial, _super);
  46211. /**
  46212. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46213. *
  46214. * @param name The material name
  46215. * @param scene The scene the material will be use in.
  46216. */
  46217. function PBRMetallicRoughnessMaterial(name, scene) {
  46218. var _this = _super.call(this, name, scene) || this;
  46219. _this._useRoughnessFromMetallicTextureAlpha = false;
  46220. _this._useRoughnessFromMetallicTextureGreen = true;
  46221. _this._useMetallnessFromMetallicTextureBlue = true;
  46222. _this.metallic = 1.0;
  46223. _this.roughness = 1.0;
  46224. return _this;
  46225. }
  46226. /**
  46227. * Return the currrent class name of the material.
  46228. */
  46229. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46230. return "PBRMetallicRoughnessMaterial";
  46231. };
  46232. /**
  46233. * Return the active textures of the material.
  46234. */
  46235. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46236. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46237. if (this.baseTexture) {
  46238. activeTextures.push(this.baseTexture);
  46239. }
  46240. if (this.metallicRoughnessTexture) {
  46241. activeTextures.push(this.metallicRoughnessTexture);
  46242. }
  46243. return activeTextures;
  46244. };
  46245. /**
  46246. * Checks to see if a texture is used in the material.
  46247. * @param texture - Base texture to use.
  46248. * @returns - Boolean specifying if a texture is used in the material.
  46249. */
  46250. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46251. if (_super.prototype.hasTexture.call(this, texture)) {
  46252. return true;
  46253. }
  46254. if (this.baseTexture === texture) {
  46255. return true;
  46256. }
  46257. if (this.metallicRoughnessTexture === texture) {
  46258. return true;
  46259. }
  46260. return false;
  46261. };
  46262. /**
  46263. * Makes a duplicate of the current material.
  46264. * @param name - name to use for the new material.
  46265. */
  46266. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46267. var _this = this;
  46268. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46269. clone.id = name;
  46270. clone.name = name;
  46271. return clone;
  46272. };
  46273. /**
  46274. * Serialize the material to a parsable JSON object.
  46275. */
  46276. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46277. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46278. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46279. return serializationObject;
  46280. };
  46281. /**
  46282. * Parses a JSON object correponding to the serialize function.
  46283. */
  46284. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46285. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46286. };
  46287. __decorate([
  46288. BABYLON.serializeAsColor3(),
  46289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46290. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46291. __decorate([
  46292. BABYLON.serializeAsTexture(),
  46293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46294. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46295. __decorate([
  46296. BABYLON.serialize(),
  46297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46298. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46299. __decorate([
  46300. BABYLON.serialize(),
  46301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46302. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46303. __decorate([
  46304. BABYLON.serializeAsTexture(),
  46305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46306. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46307. return PBRMetallicRoughnessMaterial;
  46308. }(BABYLON.PBRBaseSimpleMaterial));
  46309. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46310. })(BABYLON || (BABYLON = {}));
  46311. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46312. var BABYLON;
  46313. (function (BABYLON) {
  46314. /**
  46315. * The PBR material of BJS following the specular glossiness convention.
  46316. *
  46317. * This fits to the PBR convention in the GLTF definition:
  46318. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46319. */
  46320. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46321. __extends(PBRSpecularGlossinessMaterial, _super);
  46322. /**
  46323. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46324. *
  46325. * @param name The material name
  46326. * @param scene The scene the material will be use in.
  46327. */
  46328. function PBRSpecularGlossinessMaterial(name, scene) {
  46329. var _this = _super.call(this, name, scene) || this;
  46330. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46331. return _this;
  46332. }
  46333. /**
  46334. * Return the currrent class name of the material.
  46335. */
  46336. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46337. return "PBRSpecularGlossinessMaterial";
  46338. };
  46339. /**
  46340. * Return the active textures of the material.
  46341. */
  46342. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46343. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46344. if (this.diffuseTexture) {
  46345. activeTextures.push(this.diffuseTexture);
  46346. }
  46347. if (this.specularGlossinessTexture) {
  46348. activeTextures.push(this.specularGlossinessTexture);
  46349. }
  46350. return activeTextures;
  46351. };
  46352. /**
  46353. * Checks to see if a texture is used in the material.
  46354. * @param texture - Base texture to use.
  46355. * @returns - Boolean specifying if a texture is used in the material.
  46356. */
  46357. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46358. if (_super.prototype.hasTexture.call(this, texture)) {
  46359. return true;
  46360. }
  46361. if (this.diffuseTexture === texture) {
  46362. return true;
  46363. }
  46364. if (this.specularGlossinessTexture === texture) {
  46365. return true;
  46366. }
  46367. return false;
  46368. };
  46369. /**
  46370. * Makes a duplicate of the current material.
  46371. * @param name - name to use for the new material.
  46372. */
  46373. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46374. var _this = this;
  46375. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46376. clone.id = name;
  46377. clone.name = name;
  46378. return clone;
  46379. };
  46380. /**
  46381. * Serialize the material to a parsable JSON object.
  46382. */
  46383. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46384. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46385. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46386. return serializationObject;
  46387. };
  46388. /**
  46389. * Parses a JSON object correponding to the serialize function.
  46390. */
  46391. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46392. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46393. };
  46394. __decorate([
  46395. BABYLON.serializeAsColor3("diffuse"),
  46396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46397. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46398. __decorate([
  46399. BABYLON.serializeAsTexture(),
  46400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46401. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46402. __decorate([
  46403. BABYLON.serializeAsColor3("specular"),
  46404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46405. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46406. __decorate([
  46407. BABYLON.serialize(),
  46408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46409. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46410. __decorate([
  46411. BABYLON.serializeAsTexture(),
  46412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46413. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46414. return PBRSpecularGlossinessMaterial;
  46415. }(BABYLON.PBRBaseSimpleMaterial));
  46416. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46417. })(BABYLON || (BABYLON = {}));
  46418. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46419. var BABYLON;
  46420. (function (BABYLON) {
  46421. BABYLON.CameraInputTypes = {};
  46422. var CameraInputsManager = /** @class */ (function () {
  46423. function CameraInputsManager(camera) {
  46424. this.attached = {};
  46425. this.camera = camera;
  46426. this.checkInputs = function () { };
  46427. }
  46428. /**
  46429. * Add an input method to a camera.
  46430. * builtin inputs example: camera.inputs.addGamepad();
  46431. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46432. * @param input camera input method
  46433. */
  46434. CameraInputsManager.prototype.add = function (input) {
  46435. var type = input.getSimpleName();
  46436. if (this.attached[type]) {
  46437. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46438. return;
  46439. }
  46440. this.attached[type] = input;
  46441. input.camera = this.camera;
  46442. //for checkInputs, we are dynamically creating a function
  46443. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46444. if (input.checkInputs) {
  46445. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46446. }
  46447. if (this.attachedElement) {
  46448. input.attachControl(this.attachedElement);
  46449. }
  46450. };
  46451. /**
  46452. * Remove a specific input method from a camera
  46453. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46454. * @param inputToRemove camera input method
  46455. */
  46456. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46457. for (var cam in this.attached) {
  46458. var input = this.attached[cam];
  46459. if (input === inputToRemove) {
  46460. input.detachControl(this.attachedElement);
  46461. input.camera = null;
  46462. delete this.attached[cam];
  46463. this.rebuildInputCheck();
  46464. }
  46465. }
  46466. };
  46467. CameraInputsManager.prototype.removeByType = function (inputType) {
  46468. for (var cam in this.attached) {
  46469. var input = this.attached[cam];
  46470. if (input.getClassName() === inputType) {
  46471. input.detachControl(this.attachedElement);
  46472. input.camera = null;
  46473. delete this.attached[cam];
  46474. this.rebuildInputCheck();
  46475. }
  46476. }
  46477. };
  46478. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46479. var current = this.checkInputs;
  46480. return function () {
  46481. current();
  46482. fn();
  46483. };
  46484. };
  46485. CameraInputsManager.prototype.attachInput = function (input) {
  46486. if (this.attachedElement) {
  46487. input.attachControl(this.attachedElement, this.noPreventDefault);
  46488. }
  46489. };
  46490. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46491. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46492. if (this.attachedElement) {
  46493. return;
  46494. }
  46495. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46496. this.attachedElement = element;
  46497. this.noPreventDefault = noPreventDefault;
  46498. for (var cam in this.attached) {
  46499. this.attached[cam].attachControl(element, noPreventDefault);
  46500. }
  46501. };
  46502. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46503. if (disconnect === void 0) { disconnect = false; }
  46504. if (this.attachedElement !== element) {
  46505. return;
  46506. }
  46507. for (var cam in this.attached) {
  46508. this.attached[cam].detachControl(element);
  46509. if (disconnect) {
  46510. this.attached[cam].camera = null;
  46511. }
  46512. }
  46513. this.attachedElement = null;
  46514. };
  46515. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46516. this.checkInputs = function () { };
  46517. for (var cam in this.attached) {
  46518. var input = this.attached[cam];
  46519. if (input.checkInputs) {
  46520. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46521. }
  46522. }
  46523. };
  46524. /**
  46525. * Remove all attached input methods from a camera
  46526. */
  46527. CameraInputsManager.prototype.clear = function () {
  46528. if (this.attachedElement) {
  46529. this.detachElement(this.attachedElement, true);
  46530. }
  46531. this.attached = {};
  46532. this.attachedElement = null;
  46533. this.checkInputs = function () { };
  46534. };
  46535. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46536. var inputs = {};
  46537. for (var cam in this.attached) {
  46538. var input = this.attached[cam];
  46539. var res = BABYLON.SerializationHelper.Serialize(input);
  46540. inputs[input.getClassName()] = res;
  46541. }
  46542. serializedCamera.inputsmgr = inputs;
  46543. };
  46544. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46545. var parsedInputs = parsedCamera.inputsmgr;
  46546. if (parsedInputs) {
  46547. this.clear();
  46548. for (var n in parsedInputs) {
  46549. var construct = BABYLON.CameraInputTypes[n];
  46550. if (construct) {
  46551. var parsedinput = parsedInputs[n];
  46552. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46553. this.add(input);
  46554. }
  46555. }
  46556. }
  46557. else {
  46558. //2016-03-08 this part is for managing backward compatibility
  46559. for (var n in this.attached) {
  46560. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46561. if (construct) {
  46562. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46563. this.remove(this.attached[n]);
  46564. this.add(input);
  46565. }
  46566. }
  46567. }
  46568. };
  46569. return CameraInputsManager;
  46570. }());
  46571. BABYLON.CameraInputsManager = CameraInputsManager;
  46572. })(BABYLON || (BABYLON = {}));
  46573. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46574. var BABYLON;
  46575. (function (BABYLON) {
  46576. var TargetCamera = /** @class */ (function (_super) {
  46577. __extends(TargetCamera, _super);
  46578. function TargetCamera(name, position, scene) {
  46579. var _this = _super.call(this, name, position, scene) || this;
  46580. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46581. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46582. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46583. _this.speed = 2.0;
  46584. _this.noRotationConstraint = false;
  46585. _this.lockedTarget = null;
  46586. _this._currentTarget = BABYLON.Vector3.Zero();
  46587. _this._viewMatrix = BABYLON.Matrix.Zero();
  46588. _this._camMatrix = BABYLON.Matrix.Zero();
  46589. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46590. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46591. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46592. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46593. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46594. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46595. _this._tempMatrix = BABYLON.Matrix.Zero();
  46596. return _this;
  46597. }
  46598. TargetCamera.prototype.getFrontPosition = function (distance) {
  46599. this.getWorldMatrix();
  46600. var direction = this.getTarget().subtract(this.position);
  46601. direction.normalize();
  46602. direction.scaleInPlace(distance);
  46603. return this.globalPosition.add(direction);
  46604. };
  46605. TargetCamera.prototype._getLockedTargetPosition = function () {
  46606. if (!this.lockedTarget) {
  46607. return null;
  46608. }
  46609. if (this.lockedTarget.absolutePosition) {
  46610. this.lockedTarget.computeWorldMatrix();
  46611. }
  46612. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46613. };
  46614. TargetCamera.prototype.storeState = function () {
  46615. this._storedPosition = this.position.clone();
  46616. this._storedRotation = this.rotation.clone();
  46617. if (this.rotationQuaternion) {
  46618. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46619. }
  46620. return _super.prototype.storeState.call(this);
  46621. };
  46622. /**
  46623. * Restored camera state. You must call storeState() first
  46624. */
  46625. TargetCamera.prototype._restoreStateValues = function () {
  46626. if (!_super.prototype._restoreStateValues.call(this)) {
  46627. return false;
  46628. }
  46629. this.position = this._storedPosition.clone();
  46630. this.rotation = this._storedRotation.clone();
  46631. if (this.rotationQuaternion) {
  46632. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46633. }
  46634. this.cameraDirection.copyFromFloats(0, 0, 0);
  46635. this.cameraRotation.copyFromFloats(0, 0);
  46636. return true;
  46637. };
  46638. // Cache
  46639. TargetCamera.prototype._initCache = function () {
  46640. _super.prototype._initCache.call(this);
  46641. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46642. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46643. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46644. };
  46645. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46646. if (!ignoreParentClass) {
  46647. _super.prototype._updateCache.call(this);
  46648. }
  46649. var lockedTargetPosition = this._getLockedTargetPosition();
  46650. if (!lockedTargetPosition) {
  46651. this._cache.lockedTarget = null;
  46652. }
  46653. else {
  46654. if (!this._cache.lockedTarget) {
  46655. this._cache.lockedTarget = lockedTargetPosition.clone();
  46656. }
  46657. else {
  46658. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46659. }
  46660. }
  46661. this._cache.rotation.copyFrom(this.rotation);
  46662. if (this.rotationQuaternion)
  46663. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46664. };
  46665. // Synchronized
  46666. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46667. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46668. return false;
  46669. }
  46670. var lockedTargetPosition = this._getLockedTargetPosition();
  46671. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46672. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46673. };
  46674. // Methods
  46675. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46676. var engine = this.getEngine();
  46677. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46678. };
  46679. // Target
  46680. TargetCamera.prototype.setTarget = function (target) {
  46681. this.upVector.normalize();
  46682. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46683. this._camMatrix.invert();
  46684. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46685. var vDir = target.subtract(this.position);
  46686. if (vDir.x >= 0.0) {
  46687. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46688. }
  46689. else {
  46690. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46691. }
  46692. this.rotation.z = 0;
  46693. if (isNaN(this.rotation.x)) {
  46694. this.rotation.x = 0;
  46695. }
  46696. if (isNaN(this.rotation.y)) {
  46697. this.rotation.y = 0;
  46698. }
  46699. if (isNaN(this.rotation.z)) {
  46700. this.rotation.z = 0;
  46701. }
  46702. if (this.rotationQuaternion) {
  46703. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46704. }
  46705. };
  46706. /**
  46707. * Return the current target position of the camera. This value is expressed in local space.
  46708. */
  46709. TargetCamera.prototype.getTarget = function () {
  46710. return this._currentTarget;
  46711. };
  46712. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46713. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46714. };
  46715. TargetCamera.prototype._updatePosition = function () {
  46716. if (this.parent) {
  46717. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46718. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46719. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46720. return;
  46721. }
  46722. this.position.addInPlace(this.cameraDirection);
  46723. };
  46724. TargetCamera.prototype._checkInputs = function () {
  46725. var needToMove = this._decideIfNeedsToMove();
  46726. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46727. // Move
  46728. if (needToMove) {
  46729. this._updatePosition();
  46730. }
  46731. // Rotate
  46732. if (needToRotate) {
  46733. this.rotation.x += this.cameraRotation.x;
  46734. this.rotation.y += this.cameraRotation.y;
  46735. //rotate, if quaternion is set and rotation was used
  46736. if (this.rotationQuaternion) {
  46737. var len = this.rotation.lengthSquared();
  46738. if (len) {
  46739. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46740. }
  46741. }
  46742. if (!this.noRotationConstraint) {
  46743. var limit = (Math.PI / 2) * 0.95;
  46744. if (this.rotation.x > limit)
  46745. this.rotation.x = limit;
  46746. if (this.rotation.x < -limit)
  46747. this.rotation.x = -limit;
  46748. }
  46749. }
  46750. // Inertia
  46751. if (needToMove) {
  46752. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46753. this.cameraDirection.x = 0;
  46754. }
  46755. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46756. this.cameraDirection.y = 0;
  46757. }
  46758. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46759. this.cameraDirection.z = 0;
  46760. }
  46761. this.cameraDirection.scaleInPlace(this.inertia);
  46762. }
  46763. if (needToRotate) {
  46764. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46765. this.cameraRotation.x = 0;
  46766. }
  46767. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46768. this.cameraRotation.y = 0;
  46769. }
  46770. this.cameraRotation.scaleInPlace(this.inertia);
  46771. }
  46772. _super.prototype._checkInputs.call(this);
  46773. };
  46774. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46775. if (this.rotationQuaternion) {
  46776. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46777. }
  46778. else {
  46779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46780. }
  46781. //update the up vector!
  46782. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46783. };
  46784. TargetCamera.prototype._getViewMatrix = function () {
  46785. if (this.lockedTarget) {
  46786. this.setTarget(this._getLockedTargetPosition());
  46787. }
  46788. // Compute
  46789. this._updateCameraRotationMatrix();
  46790. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46791. // Computing target and final matrix
  46792. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46793. if (this.getScene().useRightHandedSystem) {
  46794. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46795. }
  46796. else {
  46797. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46798. }
  46799. return this._viewMatrix;
  46800. };
  46801. /**
  46802. * @override
  46803. * Override Camera.createRigCamera
  46804. */
  46805. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46806. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46807. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46808. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46809. if (!this.rotationQuaternion) {
  46810. this.rotationQuaternion = new BABYLON.Quaternion();
  46811. }
  46812. rigCamera._cameraRigParams = {};
  46813. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46814. }
  46815. return rigCamera;
  46816. }
  46817. return null;
  46818. };
  46819. /**
  46820. * @override
  46821. * Override Camera._updateRigCameras
  46822. */
  46823. TargetCamera.prototype._updateRigCameras = function () {
  46824. var camLeft = this._rigCameras[0];
  46825. var camRight = this._rigCameras[1];
  46826. switch (this.cameraRigMode) {
  46827. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46828. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46829. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46830. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46831. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46832. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46833. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46834. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46835. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46836. camLeft.setTarget(this.getTarget());
  46837. camRight.setTarget(this.getTarget());
  46838. break;
  46839. case BABYLON.Camera.RIG_MODE_VR:
  46840. if (camLeft.rotationQuaternion) {
  46841. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46842. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46843. }
  46844. else {
  46845. camLeft.rotation.copyFrom(this.rotation);
  46846. camRight.rotation.copyFrom(this.rotation);
  46847. }
  46848. camLeft.position.copyFrom(this.position);
  46849. camRight.position.copyFrom(this.position);
  46850. break;
  46851. }
  46852. _super.prototype._updateRigCameras.call(this);
  46853. };
  46854. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46855. if (!this._rigCamTransformMatrix) {
  46856. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46857. }
  46858. var target = this.getTarget();
  46859. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46860. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46861. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46862. };
  46863. TargetCamera.prototype.getClassName = function () {
  46864. return "TargetCamera";
  46865. };
  46866. __decorate([
  46867. BABYLON.serializeAsVector3()
  46868. ], TargetCamera.prototype, "rotation", void 0);
  46869. __decorate([
  46870. BABYLON.serialize()
  46871. ], TargetCamera.prototype, "speed", void 0);
  46872. __decorate([
  46873. BABYLON.serializeAsMeshReference("lockedTargetId")
  46874. ], TargetCamera.prototype, "lockedTarget", void 0);
  46875. return TargetCamera;
  46876. }(BABYLON.Camera));
  46877. BABYLON.TargetCamera = TargetCamera;
  46878. })(BABYLON || (BABYLON = {}));
  46879. //# sourceMappingURL=babylon.targetCamera.js.map
  46880. var BABYLON;
  46881. (function (BABYLON) {
  46882. var FreeCameraMouseInput = /** @class */ (function () {
  46883. function FreeCameraMouseInput(touchEnabled) {
  46884. if (touchEnabled === void 0) { touchEnabled = true; }
  46885. this.touchEnabled = touchEnabled;
  46886. this.buttons = [0, 1, 2];
  46887. this.angularSensibility = 2000.0;
  46888. this.previousPosition = null;
  46889. }
  46890. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46891. var _this = this;
  46892. var engine = this.camera.getEngine();
  46893. if (!this._pointerInput) {
  46894. this._pointerInput = function (p, s) {
  46895. var evt = p.event;
  46896. if (engine.isInVRExclusivePointerMode) {
  46897. return;
  46898. }
  46899. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46900. return;
  46901. }
  46902. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46903. return;
  46904. }
  46905. var srcElement = (evt.srcElement || evt.target);
  46906. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46907. try {
  46908. srcElement.setPointerCapture(evt.pointerId);
  46909. }
  46910. catch (e) {
  46911. //Nothing to do with the error. Execution will continue.
  46912. }
  46913. _this.previousPosition = {
  46914. x: evt.clientX,
  46915. y: evt.clientY
  46916. };
  46917. if (!noPreventDefault) {
  46918. evt.preventDefault();
  46919. element.focus();
  46920. }
  46921. }
  46922. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46923. try {
  46924. srcElement.releasePointerCapture(evt.pointerId);
  46925. }
  46926. catch (e) {
  46927. //Nothing to do with the error.
  46928. }
  46929. _this.previousPosition = null;
  46930. if (!noPreventDefault) {
  46931. evt.preventDefault();
  46932. }
  46933. }
  46934. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46935. if (!_this.previousPosition || engine.isPointerLock) {
  46936. return;
  46937. }
  46938. var offsetX = evt.clientX - _this.previousPosition.x;
  46939. var offsetY = evt.clientY - _this.previousPosition.y;
  46940. if (_this.camera.getScene().useRightHandedSystem) {
  46941. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46942. }
  46943. else {
  46944. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46945. }
  46946. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46947. _this.previousPosition = {
  46948. x: evt.clientX,
  46949. y: evt.clientY
  46950. };
  46951. if (!noPreventDefault) {
  46952. evt.preventDefault();
  46953. }
  46954. }
  46955. };
  46956. }
  46957. this._onMouseMove = function (evt) {
  46958. if (!engine.isPointerLock) {
  46959. return;
  46960. }
  46961. if (engine.isInVRExclusivePointerMode) {
  46962. return;
  46963. }
  46964. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46965. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46966. if (_this.camera.getScene().useRightHandedSystem) {
  46967. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46968. }
  46969. else {
  46970. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46971. }
  46972. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46973. _this.previousPosition = null;
  46974. if (!noPreventDefault) {
  46975. evt.preventDefault();
  46976. }
  46977. };
  46978. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46979. element.addEventListener("mousemove", this._onMouseMove, false);
  46980. };
  46981. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46982. if (this._observer && element) {
  46983. this.camera.getScene().onPointerObservable.remove(this._observer);
  46984. if (this._onMouseMove) {
  46985. element.removeEventListener("mousemove", this._onMouseMove);
  46986. }
  46987. this._observer = null;
  46988. this._onMouseMove = null;
  46989. this.previousPosition = null;
  46990. }
  46991. };
  46992. FreeCameraMouseInput.prototype.getClassName = function () {
  46993. return "FreeCameraMouseInput";
  46994. };
  46995. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46996. return "mouse";
  46997. };
  46998. __decorate([
  46999. BABYLON.serialize()
  47000. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47001. __decorate([
  47002. BABYLON.serialize()
  47003. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47004. return FreeCameraMouseInput;
  47005. }());
  47006. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47007. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47008. })(BABYLON || (BABYLON = {}));
  47009. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47010. var BABYLON;
  47011. (function (BABYLON) {
  47012. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47013. function FreeCameraKeyboardMoveInput() {
  47014. this._keys = new Array();
  47015. this.keysUp = [38];
  47016. this.keysDown = [40];
  47017. this.keysLeft = [37];
  47018. this.keysRight = [39];
  47019. }
  47020. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47021. var _this = this;
  47022. if (this._onCanvasBlurObserver) {
  47023. return;
  47024. }
  47025. this._scene = this.camera.getScene();
  47026. this._engine = this._scene.getEngine();
  47027. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47028. _this._keys = [];
  47029. });
  47030. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47031. var evt = info.event;
  47032. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47033. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47034. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47035. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47036. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47037. var index = _this._keys.indexOf(evt.keyCode);
  47038. if (index === -1) {
  47039. _this._keys.push(evt.keyCode);
  47040. }
  47041. if (!noPreventDefault) {
  47042. evt.preventDefault();
  47043. }
  47044. }
  47045. }
  47046. else {
  47047. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47048. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47049. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47050. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47051. var index = _this._keys.indexOf(evt.keyCode);
  47052. if (index >= 0) {
  47053. _this._keys.splice(index, 1);
  47054. }
  47055. if (!noPreventDefault) {
  47056. evt.preventDefault();
  47057. }
  47058. }
  47059. }
  47060. });
  47061. };
  47062. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47063. if (this._scene) {
  47064. if (this._onKeyboardObserver) {
  47065. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47066. }
  47067. if (this._onCanvasBlurObserver) {
  47068. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47069. }
  47070. this._onKeyboardObserver = null;
  47071. this._onCanvasBlurObserver = null;
  47072. }
  47073. this._keys = [];
  47074. };
  47075. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47076. if (this._onKeyboardObserver) {
  47077. var camera = this.camera;
  47078. // Keyboard
  47079. for (var index = 0; index < this._keys.length; index++) {
  47080. var keyCode = this._keys[index];
  47081. var speed = camera._computeLocalCameraSpeed();
  47082. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47083. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47084. }
  47085. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47086. camera._localDirection.copyFromFloats(0, 0, speed);
  47087. }
  47088. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47089. camera._localDirection.copyFromFloats(speed, 0, 0);
  47090. }
  47091. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47092. camera._localDirection.copyFromFloats(0, 0, -speed);
  47093. }
  47094. if (camera.getScene().useRightHandedSystem) {
  47095. camera._localDirection.z *= -1;
  47096. }
  47097. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47098. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47099. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47100. }
  47101. }
  47102. };
  47103. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47104. return "FreeCameraKeyboardMoveInput";
  47105. };
  47106. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47107. this._keys = [];
  47108. };
  47109. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47110. return "keyboard";
  47111. };
  47112. __decorate([
  47113. BABYLON.serialize()
  47114. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47115. __decorate([
  47116. BABYLON.serialize()
  47117. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47118. __decorate([
  47119. BABYLON.serialize()
  47120. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47121. __decorate([
  47122. BABYLON.serialize()
  47123. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47124. return FreeCameraKeyboardMoveInput;
  47125. }());
  47126. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47127. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47128. })(BABYLON || (BABYLON = {}));
  47129. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47130. var BABYLON;
  47131. (function (BABYLON) {
  47132. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47133. __extends(FreeCameraInputsManager, _super);
  47134. function FreeCameraInputsManager(camera) {
  47135. return _super.call(this, camera) || this;
  47136. }
  47137. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47138. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47139. return this;
  47140. };
  47141. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47142. if (touchEnabled === void 0) { touchEnabled = true; }
  47143. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47144. return this;
  47145. };
  47146. FreeCameraInputsManager.prototype.addGamepad = function () {
  47147. this.add(new BABYLON.FreeCameraGamepadInput());
  47148. return this;
  47149. };
  47150. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47151. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47152. return this;
  47153. };
  47154. FreeCameraInputsManager.prototype.addTouch = function () {
  47155. this.add(new BABYLON.FreeCameraTouchInput());
  47156. return this;
  47157. };
  47158. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47159. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47160. return this;
  47161. };
  47162. return FreeCameraInputsManager;
  47163. }(BABYLON.CameraInputsManager));
  47164. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47165. })(BABYLON || (BABYLON = {}));
  47166. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47167. var BABYLON;
  47168. (function (BABYLON) {
  47169. var FreeCamera = /** @class */ (function (_super) {
  47170. __extends(FreeCamera, _super);
  47171. function FreeCamera(name, position, scene) {
  47172. var _this = _super.call(this, name, position, scene) || this;
  47173. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47174. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47175. _this.checkCollisions = false;
  47176. _this.applyGravity = false;
  47177. _this._needMoveForGravity = false;
  47178. _this._oldPosition = BABYLON.Vector3.Zero();
  47179. _this._diffPosition = BABYLON.Vector3.Zero();
  47180. _this._newPosition = BABYLON.Vector3.Zero();
  47181. // Collisions
  47182. _this._collisionMask = -1;
  47183. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47184. if (collidedMesh === void 0) { collidedMesh = null; }
  47185. //TODO move this to the collision coordinator!
  47186. if (_this.getScene().workerCollisions)
  47187. newPosition.multiplyInPlace(_this._collider._radius);
  47188. var updatePosition = function (newPos) {
  47189. _this._newPosition.copyFrom(newPos);
  47190. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47191. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47192. _this.position.addInPlace(_this._diffPosition);
  47193. if (_this.onCollide && collidedMesh) {
  47194. _this.onCollide(collidedMesh);
  47195. }
  47196. }
  47197. };
  47198. updatePosition(newPosition);
  47199. };
  47200. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47201. _this.inputs.addKeyboard().addMouse();
  47202. return _this;
  47203. }
  47204. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47205. //-- begin properties for backward compatibility for inputs
  47206. /**
  47207. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47208. * Higher values reduce sensitivity.
  47209. */
  47210. get: function () {
  47211. var mouse = this.inputs.attached["mouse"];
  47212. if (mouse)
  47213. return mouse.angularSensibility;
  47214. return 0;
  47215. },
  47216. /**
  47217. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47218. * Higher values reduce sensitivity.
  47219. */
  47220. set: function (value) {
  47221. var mouse = this.inputs.attached["mouse"];
  47222. if (mouse)
  47223. mouse.angularSensibility = value;
  47224. },
  47225. enumerable: true,
  47226. configurable: true
  47227. });
  47228. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47229. get: function () {
  47230. var keyboard = this.inputs.attached["keyboard"];
  47231. if (keyboard)
  47232. return keyboard.keysUp;
  47233. return [];
  47234. },
  47235. set: function (value) {
  47236. var keyboard = this.inputs.attached["keyboard"];
  47237. if (keyboard)
  47238. keyboard.keysUp = value;
  47239. },
  47240. enumerable: true,
  47241. configurable: true
  47242. });
  47243. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47244. get: function () {
  47245. var keyboard = this.inputs.attached["keyboard"];
  47246. if (keyboard)
  47247. return keyboard.keysDown;
  47248. return [];
  47249. },
  47250. set: function (value) {
  47251. var keyboard = this.inputs.attached["keyboard"];
  47252. if (keyboard)
  47253. keyboard.keysDown = value;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47259. get: function () {
  47260. var keyboard = this.inputs.attached["keyboard"];
  47261. if (keyboard)
  47262. return keyboard.keysLeft;
  47263. return [];
  47264. },
  47265. set: function (value) {
  47266. var keyboard = this.inputs.attached["keyboard"];
  47267. if (keyboard)
  47268. keyboard.keysLeft = value;
  47269. },
  47270. enumerable: true,
  47271. configurable: true
  47272. });
  47273. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47274. get: function () {
  47275. var keyboard = this.inputs.attached["keyboard"];
  47276. if (keyboard)
  47277. return keyboard.keysRight;
  47278. return [];
  47279. },
  47280. set: function (value) {
  47281. var keyboard = this.inputs.attached["keyboard"];
  47282. if (keyboard)
  47283. keyboard.keysRight = value;
  47284. },
  47285. enumerable: true,
  47286. configurable: true
  47287. });
  47288. // Controls
  47289. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47290. this.inputs.attachElement(element, noPreventDefault);
  47291. };
  47292. FreeCamera.prototype.detachControl = function (element) {
  47293. this.inputs.detachElement(element);
  47294. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47295. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47296. };
  47297. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47298. get: function () {
  47299. return this._collisionMask;
  47300. },
  47301. set: function (mask) {
  47302. this._collisionMask = !isNaN(mask) ? mask : -1;
  47303. },
  47304. enumerable: true,
  47305. configurable: true
  47306. });
  47307. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47308. var globalPosition;
  47309. if (this.parent) {
  47310. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47311. }
  47312. else {
  47313. globalPosition = this.position;
  47314. }
  47315. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47316. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47317. if (!this._collider) {
  47318. this._collider = new BABYLON.Collider();
  47319. }
  47320. this._collider._radius = this.ellipsoid;
  47321. this._collider.collisionMask = this._collisionMask;
  47322. //no need for clone, as long as gravity is not on.
  47323. var actualDisplacement = displacement;
  47324. //add gravity to the direction to prevent the dual-collision checking
  47325. if (this.applyGravity) {
  47326. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47327. actualDisplacement = displacement.add(this.getScene().gravity);
  47328. }
  47329. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47330. };
  47331. FreeCamera.prototype._checkInputs = function () {
  47332. if (!this._localDirection) {
  47333. this._localDirection = BABYLON.Vector3.Zero();
  47334. this._transformedDirection = BABYLON.Vector3.Zero();
  47335. }
  47336. this.inputs.checkInputs();
  47337. _super.prototype._checkInputs.call(this);
  47338. };
  47339. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47340. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47341. };
  47342. FreeCamera.prototype._updatePosition = function () {
  47343. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47344. this._collideWithWorld(this.cameraDirection);
  47345. }
  47346. else {
  47347. _super.prototype._updatePosition.call(this);
  47348. }
  47349. };
  47350. FreeCamera.prototype.dispose = function () {
  47351. this.inputs.clear();
  47352. _super.prototype.dispose.call(this);
  47353. };
  47354. FreeCamera.prototype.getClassName = function () {
  47355. return "FreeCamera";
  47356. };
  47357. __decorate([
  47358. BABYLON.serializeAsVector3()
  47359. ], FreeCamera.prototype, "ellipsoid", void 0);
  47360. __decorate([
  47361. BABYLON.serializeAsVector3()
  47362. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47363. __decorate([
  47364. BABYLON.serialize()
  47365. ], FreeCamera.prototype, "checkCollisions", void 0);
  47366. __decorate([
  47367. BABYLON.serialize()
  47368. ], FreeCamera.prototype, "applyGravity", void 0);
  47369. return FreeCamera;
  47370. }(BABYLON.TargetCamera));
  47371. BABYLON.FreeCamera = FreeCamera;
  47372. })(BABYLON || (BABYLON = {}));
  47373. //# sourceMappingURL=babylon.freeCamera.js.map
  47374. var BABYLON;
  47375. (function (BABYLON) {
  47376. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47377. function ArcRotateCameraKeyboardMoveInput() {
  47378. this._keys = new Array();
  47379. this.keysUp = [38];
  47380. this.keysDown = [40];
  47381. this.keysLeft = [37];
  47382. this.keysRight = [39];
  47383. this.keysReset = [220];
  47384. this.panningSensibility = 50.0;
  47385. this.zoomingSensibility = 25.0;
  47386. this.useAltToZoom = true;
  47387. }
  47388. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47389. var _this = this;
  47390. if (this._onCanvasBlurObserver) {
  47391. return;
  47392. }
  47393. this._scene = this.camera.getScene();
  47394. this._engine = this._scene.getEngine();
  47395. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47396. _this._keys = [];
  47397. });
  47398. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47399. var evt = info.event;
  47400. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47401. _this._ctrlPressed = evt.ctrlKey;
  47402. _this._altPressed = evt.altKey;
  47403. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47404. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47405. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47406. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47407. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47408. var index = _this._keys.indexOf(evt.keyCode);
  47409. if (index === -1) {
  47410. _this._keys.push(evt.keyCode);
  47411. }
  47412. if (evt.preventDefault) {
  47413. if (!noPreventDefault) {
  47414. evt.preventDefault();
  47415. }
  47416. }
  47417. }
  47418. }
  47419. else {
  47420. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47421. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47422. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47423. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47424. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47425. var index = _this._keys.indexOf(evt.keyCode);
  47426. if (index >= 0) {
  47427. _this._keys.splice(index, 1);
  47428. }
  47429. if (evt.preventDefault) {
  47430. if (!noPreventDefault) {
  47431. evt.preventDefault();
  47432. }
  47433. }
  47434. }
  47435. }
  47436. });
  47437. };
  47438. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47439. if (this._scene) {
  47440. if (this._onKeyboardObserver) {
  47441. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47442. }
  47443. if (this._onCanvasBlurObserver) {
  47444. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47445. }
  47446. this._onKeyboardObserver = null;
  47447. this._onCanvasBlurObserver = null;
  47448. }
  47449. this._keys = [];
  47450. };
  47451. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47452. if (this._onKeyboardObserver) {
  47453. var camera = this.camera;
  47454. for (var index = 0; index < this._keys.length; index++) {
  47455. var keyCode = this._keys[index];
  47456. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47457. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47458. camera.inertialPanningX -= 1 / this.panningSensibility;
  47459. }
  47460. else {
  47461. camera.inertialAlphaOffset -= 0.01;
  47462. }
  47463. }
  47464. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47465. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47466. camera.inertialPanningY += 1 / this.panningSensibility;
  47467. }
  47468. else if (this._altPressed && this.useAltToZoom) {
  47469. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47470. }
  47471. else {
  47472. camera.inertialBetaOffset -= 0.01;
  47473. }
  47474. }
  47475. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47476. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47477. camera.inertialPanningX += 1 / this.panningSensibility;
  47478. }
  47479. else {
  47480. camera.inertialAlphaOffset += 0.01;
  47481. }
  47482. }
  47483. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47484. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47485. camera.inertialPanningY -= 1 / this.panningSensibility;
  47486. }
  47487. else if (this._altPressed && this.useAltToZoom) {
  47488. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47489. }
  47490. else {
  47491. camera.inertialBetaOffset += 0.01;
  47492. }
  47493. }
  47494. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47495. camera.restoreState();
  47496. }
  47497. }
  47498. }
  47499. };
  47500. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47501. return "ArcRotateCameraKeyboardMoveInput";
  47502. };
  47503. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47504. return "keyboard";
  47505. };
  47506. __decorate([
  47507. BABYLON.serialize()
  47508. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47509. __decorate([
  47510. BABYLON.serialize()
  47511. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47512. __decorate([
  47513. BABYLON.serialize()
  47514. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47515. __decorate([
  47516. BABYLON.serialize()
  47517. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47518. __decorate([
  47519. BABYLON.serialize()
  47520. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47521. __decorate([
  47522. BABYLON.serialize()
  47523. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47524. __decorate([
  47525. BABYLON.serialize()
  47526. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47527. __decorate([
  47528. BABYLON.serialize()
  47529. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47530. return ArcRotateCameraKeyboardMoveInput;
  47531. }());
  47532. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47533. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47534. })(BABYLON || (BABYLON = {}));
  47535. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47536. var BABYLON;
  47537. (function (BABYLON) {
  47538. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47539. function ArcRotateCameraMouseWheelInput() {
  47540. this.wheelPrecision = 3.0;
  47541. /**
  47542. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47543. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47544. */
  47545. this.wheelDeltaPercentage = 0;
  47546. }
  47547. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47548. var _this = this;
  47549. this._wheel = function (p, s) {
  47550. //sanity check - this should be a PointerWheel event.
  47551. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47552. return;
  47553. var event = p.event;
  47554. var delta = 0;
  47555. if (event.wheelDelta) {
  47556. if (_this.wheelDeltaPercentage) {
  47557. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47558. if (event.wheelDelta > 0) {
  47559. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47560. }
  47561. else {
  47562. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47563. }
  47564. }
  47565. else {
  47566. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47567. }
  47568. }
  47569. else if (event.detail) {
  47570. delta = -event.detail / _this.wheelPrecision;
  47571. }
  47572. if (delta)
  47573. _this.camera.inertialRadiusOffset += delta;
  47574. if (event.preventDefault) {
  47575. if (!noPreventDefault) {
  47576. event.preventDefault();
  47577. }
  47578. }
  47579. };
  47580. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47581. };
  47582. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47583. if (this._observer && element) {
  47584. this.camera.getScene().onPointerObservable.remove(this._observer);
  47585. this._observer = null;
  47586. this._wheel = null;
  47587. }
  47588. };
  47589. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47590. return "ArcRotateCameraMouseWheelInput";
  47591. };
  47592. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47593. return "mousewheel";
  47594. };
  47595. __decorate([
  47596. BABYLON.serialize()
  47597. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47598. __decorate([
  47599. BABYLON.serialize()
  47600. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47601. return ArcRotateCameraMouseWheelInput;
  47602. }());
  47603. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47604. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47605. })(BABYLON || (BABYLON = {}));
  47606. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47607. var BABYLON;
  47608. (function (BABYLON) {
  47609. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47610. function ArcRotateCameraPointersInput() {
  47611. this.buttons = [0, 1, 2];
  47612. this.angularSensibilityX = 1000.0;
  47613. this.angularSensibilityY = 1000.0;
  47614. this.pinchPrecision = 12.0;
  47615. /**
  47616. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47617. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47618. */
  47619. this.pinchDeltaPercentage = 0;
  47620. this.panningSensibility = 1000.0;
  47621. this.multiTouchPanning = true;
  47622. this.multiTouchPanAndZoom = true;
  47623. this._isPanClick = false;
  47624. this.pinchInwards = true;
  47625. }
  47626. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47627. var _this = this;
  47628. var engine = this.camera.getEngine();
  47629. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47630. var pointA = null;
  47631. var pointB = null;
  47632. var previousPinchSquaredDistance = 0;
  47633. var initialDistance = 0;
  47634. var twoFingerActivityCount = 0;
  47635. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47636. this._pointerInput = function (p, s) {
  47637. var evt = p.event;
  47638. var isTouch = p.event.pointerType === "touch";
  47639. if (engine.isInVRExclusivePointerMode) {
  47640. return;
  47641. }
  47642. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47643. return;
  47644. }
  47645. var srcElement = (evt.srcElement || evt.target);
  47646. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47647. try {
  47648. srcElement.setPointerCapture(evt.pointerId);
  47649. }
  47650. catch (e) {
  47651. //Nothing to do with the error. Execution will continue.
  47652. }
  47653. // Manage panning with pan button click
  47654. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47655. // manage pointers
  47656. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47657. if (pointA === null) {
  47658. pointA = cacheSoloPointer;
  47659. }
  47660. else if (pointB === null) {
  47661. pointB = cacheSoloPointer;
  47662. }
  47663. if (!noPreventDefault) {
  47664. evt.preventDefault();
  47665. element.focus();
  47666. }
  47667. }
  47668. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47669. _this.camera.restoreState();
  47670. }
  47671. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47672. try {
  47673. srcElement.releasePointerCapture(evt.pointerId);
  47674. }
  47675. catch (e) {
  47676. //Nothing to do with the error.
  47677. }
  47678. cacheSoloPointer = null;
  47679. previousPinchSquaredDistance = 0;
  47680. previousMultiTouchPanPosition.isPaning = false;
  47681. previousMultiTouchPanPosition.isPinching = false;
  47682. twoFingerActivityCount = 0;
  47683. initialDistance = 0;
  47684. if (!isTouch) {
  47685. pointB = null; // Mouse and pen are mono pointer
  47686. }
  47687. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47688. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47689. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47690. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47691. if (engine._badOS) {
  47692. pointA = pointB = null;
  47693. }
  47694. else {
  47695. //only remove the impacted pointer in case of multitouch allowing on most
  47696. //platforms switching from rotate to zoom and pan seamlessly.
  47697. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47698. pointA = pointB;
  47699. pointB = null;
  47700. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47701. }
  47702. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47703. pointB = null;
  47704. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47705. }
  47706. else {
  47707. pointA = pointB = null;
  47708. }
  47709. }
  47710. if (!noPreventDefault) {
  47711. evt.preventDefault();
  47712. }
  47713. }
  47714. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47715. if (!noPreventDefault) {
  47716. evt.preventDefault();
  47717. }
  47718. // One button down
  47719. if (pointA && pointB === null && cacheSoloPointer) {
  47720. if (_this.panningSensibility !== 0 &&
  47721. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47722. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47723. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47724. }
  47725. else {
  47726. var offsetX = evt.clientX - cacheSoloPointer.x;
  47727. var offsetY = evt.clientY - cacheSoloPointer.y;
  47728. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47729. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47730. }
  47731. cacheSoloPointer.x = evt.clientX;
  47732. cacheSoloPointer.y = evt.clientY;
  47733. }
  47734. // Two buttons down: pinch/pan
  47735. else if (pointA && pointB) {
  47736. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47737. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47738. ed.x = evt.clientX;
  47739. ed.y = evt.clientY;
  47740. var direction = _this.pinchInwards ? 1 : -1;
  47741. var distX = pointA.x - pointB.x;
  47742. var distY = pointA.y - pointB.y;
  47743. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47744. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47745. if (previousPinchSquaredDistance === 0) {
  47746. initialDistance = pinchDistance;
  47747. previousPinchSquaredDistance = pinchSquaredDistance;
  47748. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47749. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47750. return;
  47751. }
  47752. if (_this.multiTouchPanAndZoom) {
  47753. if (_this.pinchDeltaPercentage) {
  47754. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47755. }
  47756. else {
  47757. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47758. (_this.pinchPrecision *
  47759. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47760. direction);
  47761. }
  47762. if (_this.panningSensibility !== 0) {
  47763. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47764. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47765. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47766. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47767. previousMultiTouchPanPosition.x = pointersCenterX;
  47768. previousMultiTouchPanPosition.y = pointersCenterY;
  47769. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47770. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47771. }
  47772. }
  47773. else {
  47774. twoFingerActivityCount++;
  47775. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47776. if (_this.pinchDeltaPercentage) {
  47777. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47778. }
  47779. else {
  47780. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47781. (_this.pinchPrecision *
  47782. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47783. direction);
  47784. }
  47785. previousMultiTouchPanPosition.isPaning = false;
  47786. previousMultiTouchPanPosition.isPinching = true;
  47787. }
  47788. else {
  47789. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47790. if (!previousMultiTouchPanPosition.isPaning) {
  47791. previousMultiTouchPanPosition.isPaning = true;
  47792. previousMultiTouchPanPosition.isPinching = false;
  47793. previousMultiTouchPanPosition.x = ed.x;
  47794. previousMultiTouchPanPosition.y = ed.y;
  47795. return;
  47796. }
  47797. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47798. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47799. }
  47800. }
  47801. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47802. previousMultiTouchPanPosition.x = ed.x;
  47803. previousMultiTouchPanPosition.y = ed.y;
  47804. }
  47805. }
  47806. previousPinchSquaredDistance = pinchSquaredDistance;
  47807. }
  47808. }
  47809. };
  47810. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47811. this._onContextMenu = function (evt) {
  47812. evt.preventDefault();
  47813. };
  47814. if (!this.camera._useCtrlForPanning) {
  47815. element.addEventListener("contextmenu", this._onContextMenu, false);
  47816. }
  47817. this._onLostFocus = function () {
  47818. //this._keys = [];
  47819. pointA = pointB = null;
  47820. previousPinchSquaredDistance = 0;
  47821. previousMultiTouchPanPosition.isPaning = false;
  47822. previousMultiTouchPanPosition.isPinching = false;
  47823. twoFingerActivityCount = 0;
  47824. cacheSoloPointer = null;
  47825. initialDistance = 0;
  47826. };
  47827. this._onMouseMove = function (evt) {
  47828. if (!engine.isPointerLock) {
  47829. return;
  47830. }
  47831. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47832. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47833. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47834. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47835. if (!noPreventDefault) {
  47836. evt.preventDefault();
  47837. }
  47838. };
  47839. this._onGestureStart = function (e) {
  47840. if (window.MSGesture === undefined) {
  47841. return;
  47842. }
  47843. if (!_this._MSGestureHandler) {
  47844. _this._MSGestureHandler = new MSGesture();
  47845. _this._MSGestureHandler.target = element;
  47846. }
  47847. _this._MSGestureHandler.addPointer(e.pointerId);
  47848. };
  47849. this._onGesture = function (e) {
  47850. _this.camera.radius *= e.scale;
  47851. if (e.preventDefault) {
  47852. if (!noPreventDefault) {
  47853. e.stopPropagation();
  47854. e.preventDefault();
  47855. }
  47856. }
  47857. };
  47858. element.addEventListener("mousemove", this._onMouseMove, false);
  47859. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47860. element.addEventListener("MSGestureChange", this._onGesture, false);
  47861. BABYLON.Tools.RegisterTopRootEvents([
  47862. { name: "blur", handler: this._onLostFocus }
  47863. ]);
  47864. };
  47865. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47866. if (this._onLostFocus) {
  47867. BABYLON.Tools.UnregisterTopRootEvents([
  47868. { name: "blur", handler: this._onLostFocus }
  47869. ]);
  47870. }
  47871. if (element && this._observer) {
  47872. this.camera.getScene().onPointerObservable.remove(this._observer);
  47873. this._observer = null;
  47874. if (this._onContextMenu) {
  47875. element.removeEventListener("contextmenu", this._onContextMenu);
  47876. }
  47877. if (this._onMouseMove) {
  47878. element.removeEventListener("mousemove", this._onMouseMove);
  47879. }
  47880. if (this._onGestureStart) {
  47881. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47882. }
  47883. if (this._onGesture) {
  47884. element.removeEventListener("MSGestureChange", this._onGesture);
  47885. }
  47886. this._isPanClick = false;
  47887. this.pinchInwards = true;
  47888. this._onMouseMove = null;
  47889. this._onGestureStart = null;
  47890. this._onGesture = null;
  47891. this._MSGestureHandler = null;
  47892. this._onLostFocus = null;
  47893. this._onContextMenu = null;
  47894. }
  47895. };
  47896. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47897. return "ArcRotateCameraPointersInput";
  47898. };
  47899. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47900. return "pointers";
  47901. };
  47902. __decorate([
  47903. BABYLON.serialize()
  47904. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47905. __decorate([
  47906. BABYLON.serialize()
  47907. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47908. __decorate([
  47909. BABYLON.serialize()
  47910. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47911. __decorate([
  47912. BABYLON.serialize()
  47913. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47914. __decorate([
  47915. BABYLON.serialize()
  47916. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47917. __decorate([
  47918. BABYLON.serialize()
  47919. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47920. __decorate([
  47921. BABYLON.serialize()
  47922. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47923. __decorate([
  47924. BABYLON.serialize()
  47925. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47926. return ArcRotateCameraPointersInput;
  47927. }());
  47928. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47929. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47930. })(BABYLON || (BABYLON = {}));
  47931. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47932. var BABYLON;
  47933. (function (BABYLON) {
  47934. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47935. __extends(ArcRotateCameraInputsManager, _super);
  47936. function ArcRotateCameraInputsManager(camera) {
  47937. return _super.call(this, camera) || this;
  47938. }
  47939. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47940. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47941. return this;
  47942. };
  47943. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47944. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47945. return this;
  47946. };
  47947. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47948. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47949. return this;
  47950. };
  47951. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47952. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47953. return this;
  47954. };
  47955. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47956. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47957. return this;
  47958. };
  47959. return ArcRotateCameraInputsManager;
  47960. }(BABYLON.CameraInputsManager));
  47961. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47962. })(BABYLON || (BABYLON = {}));
  47963. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47964. var BABYLON;
  47965. (function (BABYLON) {
  47966. var ArcRotateCamera = /** @class */ (function (_super) {
  47967. __extends(ArcRotateCamera, _super);
  47968. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  47969. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  47970. _this.inertialAlphaOffset = 0;
  47971. _this.inertialBetaOffset = 0;
  47972. _this.inertialRadiusOffset = 0;
  47973. _this.lowerAlphaLimit = null;
  47974. _this.upperAlphaLimit = null;
  47975. _this.lowerBetaLimit = 0.01;
  47976. _this.upperBetaLimit = Math.PI;
  47977. _this.lowerRadiusLimit = null;
  47978. _this.upperRadiusLimit = null;
  47979. _this.inertialPanningX = 0;
  47980. _this.inertialPanningY = 0;
  47981. _this.pinchToPanMaxDistance = 20;
  47982. _this.panningDistanceLimit = null;
  47983. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47984. _this.panningInertia = 0.9;
  47985. //-- end properties for backward compatibility for inputs
  47986. _this.zoomOnFactor = 1;
  47987. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47988. _this.allowUpsideDown = true;
  47989. _this._viewMatrix = new BABYLON.Matrix();
  47990. // Panning
  47991. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47992. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47993. _this.checkCollisions = false;
  47994. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47995. _this._previousPosition = BABYLON.Vector3.Zero();
  47996. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47997. _this._newPosition = BABYLON.Vector3.Zero();
  47998. _this._computationVector = BABYLON.Vector3.Zero();
  47999. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48000. if (collidedMesh === void 0) { collidedMesh = null; }
  48001. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48002. newPosition.multiplyInPlace(_this._collider._radius);
  48003. }
  48004. if (!collidedMesh) {
  48005. _this._previousPosition.copyFrom(_this.position);
  48006. }
  48007. else {
  48008. _this.setPosition(newPosition);
  48009. if (_this.onCollide) {
  48010. _this.onCollide(collidedMesh);
  48011. }
  48012. }
  48013. // Recompute because of constraints
  48014. var cosa = Math.cos(_this.alpha);
  48015. var sina = Math.sin(_this.alpha);
  48016. var cosb = Math.cos(_this.beta);
  48017. var sinb = Math.sin(_this.beta);
  48018. if (sinb === 0) {
  48019. sinb = 0.0001;
  48020. }
  48021. var target = _this._getTargetPosition();
  48022. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48023. target.addToRef(_this._computationVector, _this._newPosition);
  48024. _this.position.copyFrom(_this._newPosition);
  48025. var up = _this.upVector;
  48026. if (_this.allowUpsideDown && _this.beta < 0) {
  48027. up = up.clone();
  48028. up = up.negate();
  48029. }
  48030. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48031. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48032. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48033. _this._collisionTriggered = false;
  48034. };
  48035. _this._target = BABYLON.Vector3.Zero();
  48036. if (target) {
  48037. _this.setTarget(target);
  48038. }
  48039. _this.alpha = alpha;
  48040. _this.beta = beta;
  48041. _this.radius = radius;
  48042. _this.getViewMatrix();
  48043. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48044. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48045. return _this;
  48046. }
  48047. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48048. get: function () {
  48049. return this._target;
  48050. },
  48051. set: function (value) {
  48052. this.setTarget(value);
  48053. },
  48054. enumerable: true,
  48055. configurable: true
  48056. });
  48057. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48058. //-- begin properties for backward compatibility for inputs
  48059. get: function () {
  48060. var pointers = this.inputs.attached["pointers"];
  48061. if (pointers)
  48062. return pointers.angularSensibilityX;
  48063. return 0;
  48064. },
  48065. set: function (value) {
  48066. var pointers = this.inputs.attached["pointers"];
  48067. if (pointers) {
  48068. pointers.angularSensibilityX = value;
  48069. }
  48070. },
  48071. enumerable: true,
  48072. configurable: true
  48073. });
  48074. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48075. get: function () {
  48076. var pointers = this.inputs.attached["pointers"];
  48077. if (pointers)
  48078. return pointers.angularSensibilityY;
  48079. return 0;
  48080. },
  48081. set: function (value) {
  48082. var pointers = this.inputs.attached["pointers"];
  48083. if (pointers) {
  48084. pointers.angularSensibilityY = value;
  48085. }
  48086. },
  48087. enumerable: true,
  48088. configurable: true
  48089. });
  48090. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48091. get: function () {
  48092. var pointers = this.inputs.attached["pointers"];
  48093. if (pointers)
  48094. return pointers.pinchPrecision;
  48095. return 0;
  48096. },
  48097. set: function (value) {
  48098. var pointers = this.inputs.attached["pointers"];
  48099. if (pointers) {
  48100. pointers.pinchPrecision = value;
  48101. }
  48102. },
  48103. enumerable: true,
  48104. configurable: true
  48105. });
  48106. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48107. get: function () {
  48108. var pointers = this.inputs.attached["pointers"];
  48109. if (pointers)
  48110. return pointers.pinchDeltaPercentage;
  48111. return 0;
  48112. },
  48113. set: function (value) {
  48114. var pointers = this.inputs.attached["pointers"];
  48115. if (pointers) {
  48116. pointers.pinchDeltaPercentage = value;
  48117. }
  48118. },
  48119. enumerable: true,
  48120. configurable: true
  48121. });
  48122. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48123. get: function () {
  48124. var pointers = this.inputs.attached["pointers"];
  48125. if (pointers)
  48126. return pointers.panningSensibility;
  48127. return 0;
  48128. },
  48129. set: function (value) {
  48130. var pointers = this.inputs.attached["pointers"];
  48131. if (pointers) {
  48132. pointers.panningSensibility = value;
  48133. }
  48134. },
  48135. enumerable: true,
  48136. configurable: true
  48137. });
  48138. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48139. get: function () {
  48140. var keyboard = this.inputs.attached["keyboard"];
  48141. if (keyboard)
  48142. return keyboard.keysUp;
  48143. return [];
  48144. },
  48145. set: function (value) {
  48146. var keyboard = this.inputs.attached["keyboard"];
  48147. if (keyboard)
  48148. keyboard.keysUp = value;
  48149. },
  48150. enumerable: true,
  48151. configurable: true
  48152. });
  48153. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48154. get: function () {
  48155. var keyboard = this.inputs.attached["keyboard"];
  48156. if (keyboard)
  48157. return keyboard.keysDown;
  48158. return [];
  48159. },
  48160. set: function (value) {
  48161. var keyboard = this.inputs.attached["keyboard"];
  48162. if (keyboard)
  48163. keyboard.keysDown = value;
  48164. },
  48165. enumerable: true,
  48166. configurable: true
  48167. });
  48168. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48169. get: function () {
  48170. var keyboard = this.inputs.attached["keyboard"];
  48171. if (keyboard)
  48172. return keyboard.keysLeft;
  48173. return [];
  48174. },
  48175. set: function (value) {
  48176. var keyboard = this.inputs.attached["keyboard"];
  48177. if (keyboard)
  48178. keyboard.keysLeft = value;
  48179. },
  48180. enumerable: true,
  48181. configurable: true
  48182. });
  48183. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48184. get: function () {
  48185. var keyboard = this.inputs.attached["keyboard"];
  48186. if (keyboard)
  48187. return keyboard.keysRight;
  48188. return [];
  48189. },
  48190. set: function (value) {
  48191. var keyboard = this.inputs.attached["keyboard"];
  48192. if (keyboard)
  48193. keyboard.keysRight = value;
  48194. },
  48195. enumerable: true,
  48196. configurable: true
  48197. });
  48198. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48199. get: function () {
  48200. var mousewheel = this.inputs.attached["mousewheel"];
  48201. if (mousewheel)
  48202. return mousewheel.wheelPrecision;
  48203. return 0;
  48204. },
  48205. set: function (value) {
  48206. var mousewheel = this.inputs.attached["mousewheel"];
  48207. if (mousewheel)
  48208. mousewheel.wheelPrecision = value;
  48209. },
  48210. enumerable: true,
  48211. configurable: true
  48212. });
  48213. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48214. get: function () {
  48215. var mousewheel = this.inputs.attached["mousewheel"];
  48216. if (mousewheel)
  48217. return mousewheel.wheelDeltaPercentage;
  48218. return 0;
  48219. },
  48220. set: function (value) {
  48221. var mousewheel = this.inputs.attached["mousewheel"];
  48222. if (mousewheel)
  48223. mousewheel.wheelDeltaPercentage = value;
  48224. },
  48225. enumerable: true,
  48226. configurable: true
  48227. });
  48228. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48229. get: function () {
  48230. return this._bouncingBehavior;
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48236. get: function () {
  48237. return this._bouncingBehavior != null;
  48238. },
  48239. set: function (value) {
  48240. if (value === this.useBouncingBehavior) {
  48241. return;
  48242. }
  48243. if (value) {
  48244. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48245. this.addBehavior(this._bouncingBehavior);
  48246. }
  48247. else if (this._bouncingBehavior) {
  48248. this.removeBehavior(this._bouncingBehavior);
  48249. this._bouncingBehavior = null;
  48250. }
  48251. },
  48252. enumerable: true,
  48253. configurable: true
  48254. });
  48255. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48256. get: function () {
  48257. return this._framingBehavior;
  48258. },
  48259. enumerable: true,
  48260. configurable: true
  48261. });
  48262. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48263. get: function () {
  48264. return this._framingBehavior != null;
  48265. },
  48266. set: function (value) {
  48267. if (value === this.useFramingBehavior) {
  48268. return;
  48269. }
  48270. if (value) {
  48271. this._framingBehavior = new BABYLON.FramingBehavior();
  48272. this.addBehavior(this._framingBehavior);
  48273. }
  48274. else if (this._framingBehavior) {
  48275. this.removeBehavior(this._framingBehavior);
  48276. this._framingBehavior = null;
  48277. }
  48278. },
  48279. enumerable: true,
  48280. configurable: true
  48281. });
  48282. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48283. get: function () {
  48284. return this._autoRotationBehavior;
  48285. },
  48286. enumerable: true,
  48287. configurable: true
  48288. });
  48289. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48290. get: function () {
  48291. return this._autoRotationBehavior != null;
  48292. },
  48293. set: function (value) {
  48294. if (value === this.useAutoRotationBehavior) {
  48295. return;
  48296. }
  48297. if (value) {
  48298. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48299. this.addBehavior(this._autoRotationBehavior);
  48300. }
  48301. else if (this._autoRotationBehavior) {
  48302. this.removeBehavior(this._autoRotationBehavior);
  48303. this._autoRotationBehavior = null;
  48304. }
  48305. },
  48306. enumerable: true,
  48307. configurable: true
  48308. });
  48309. // Cache
  48310. ArcRotateCamera.prototype._initCache = function () {
  48311. _super.prototype._initCache.call(this);
  48312. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48313. this._cache.alpha = undefined;
  48314. this._cache.beta = undefined;
  48315. this._cache.radius = undefined;
  48316. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48317. };
  48318. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48319. if (!ignoreParentClass) {
  48320. _super.prototype._updateCache.call(this);
  48321. }
  48322. this._cache._target.copyFrom(this._getTargetPosition());
  48323. this._cache.alpha = this.alpha;
  48324. this._cache.beta = this.beta;
  48325. this._cache.radius = this.radius;
  48326. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48327. };
  48328. ArcRotateCamera.prototype._getTargetPosition = function () {
  48329. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48330. var pos = this._targetHost.getAbsolutePosition();
  48331. if (this._targetBoundingCenter) {
  48332. pos.addToRef(this._targetBoundingCenter, this._target);
  48333. }
  48334. else {
  48335. this._target.copyFrom(pos);
  48336. }
  48337. }
  48338. var lockedTargetPosition = this._getLockedTargetPosition();
  48339. if (lockedTargetPosition) {
  48340. return lockedTargetPosition;
  48341. }
  48342. return this._target;
  48343. };
  48344. ArcRotateCamera.prototype.storeState = function () {
  48345. this._storedAlpha = this.alpha;
  48346. this._storedBeta = this.beta;
  48347. this._storedRadius = this.radius;
  48348. this._storedTarget = this._getTargetPosition().clone();
  48349. return _super.prototype.storeState.call(this);
  48350. };
  48351. /**
  48352. * Restored camera state. You must call storeState() first
  48353. */
  48354. ArcRotateCamera.prototype._restoreStateValues = function () {
  48355. if (!_super.prototype._restoreStateValues.call(this)) {
  48356. return false;
  48357. }
  48358. this.alpha = this._storedAlpha;
  48359. this.beta = this._storedBeta;
  48360. this.radius = this._storedRadius;
  48361. this.setTarget(this._storedTarget.clone());
  48362. this.inertialAlphaOffset = 0;
  48363. this.inertialBetaOffset = 0;
  48364. this.inertialRadiusOffset = 0;
  48365. this.inertialPanningX = 0;
  48366. this.inertialPanningY = 0;
  48367. return true;
  48368. };
  48369. // Synchronized
  48370. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48371. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48372. return false;
  48373. return this._cache._target.equals(this._getTargetPosition())
  48374. && this._cache.alpha === this.alpha
  48375. && this._cache.beta === this.beta
  48376. && this._cache.radius === this.radius
  48377. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48378. };
  48379. // Methods
  48380. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48381. var _this = this;
  48382. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48383. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48384. this._useCtrlForPanning = useCtrlForPanning;
  48385. this._panningMouseButton = panningMouseButton;
  48386. this.inputs.attachElement(element, noPreventDefault);
  48387. this._reset = function () {
  48388. _this.inertialAlphaOffset = 0;
  48389. _this.inertialBetaOffset = 0;
  48390. _this.inertialRadiusOffset = 0;
  48391. _this.inertialPanningX = 0;
  48392. _this.inertialPanningY = 0;
  48393. };
  48394. };
  48395. ArcRotateCamera.prototype.detachControl = function (element) {
  48396. this.inputs.detachElement(element);
  48397. if (this._reset) {
  48398. this._reset();
  48399. }
  48400. };
  48401. ArcRotateCamera.prototype._checkInputs = function () {
  48402. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48403. if (this._collisionTriggered) {
  48404. return;
  48405. }
  48406. this.inputs.checkInputs();
  48407. // Inertia
  48408. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48409. if (this.getScene().useRightHandedSystem) {
  48410. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48411. }
  48412. else {
  48413. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48414. }
  48415. this.beta += this.inertialBetaOffset;
  48416. this.radius -= this.inertialRadiusOffset;
  48417. this.inertialAlphaOffset *= this.inertia;
  48418. this.inertialBetaOffset *= this.inertia;
  48419. this.inertialRadiusOffset *= this.inertia;
  48420. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48421. this.inertialAlphaOffset = 0;
  48422. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48423. this.inertialBetaOffset = 0;
  48424. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48425. this.inertialRadiusOffset = 0;
  48426. }
  48427. // Panning inertia
  48428. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48429. if (!this._localDirection) {
  48430. this._localDirection = BABYLON.Vector3.Zero();
  48431. this._transformedDirection = BABYLON.Vector3.Zero();
  48432. }
  48433. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48434. this._localDirection.multiplyInPlace(this.panningAxis);
  48435. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48436. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48437. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48438. if (!this.panningAxis.y) {
  48439. this._transformedDirection.y = 0;
  48440. }
  48441. if (!this._targetHost) {
  48442. if (this.panningDistanceLimit) {
  48443. this._transformedDirection.addInPlace(this._target);
  48444. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48445. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48446. this._target.copyFrom(this._transformedDirection);
  48447. }
  48448. }
  48449. else {
  48450. this._target.addInPlace(this._transformedDirection);
  48451. }
  48452. }
  48453. this.inertialPanningX *= this.panningInertia;
  48454. this.inertialPanningY *= this.panningInertia;
  48455. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48456. this.inertialPanningX = 0;
  48457. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48458. this.inertialPanningY = 0;
  48459. }
  48460. // Limits
  48461. this._checkLimits();
  48462. _super.prototype._checkInputs.call(this);
  48463. };
  48464. ArcRotateCamera.prototype._checkLimits = function () {
  48465. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48466. if (this.allowUpsideDown && this.beta > Math.PI) {
  48467. this.beta = this.beta - (2 * Math.PI);
  48468. }
  48469. }
  48470. else {
  48471. if (this.beta < this.lowerBetaLimit) {
  48472. this.beta = this.lowerBetaLimit;
  48473. }
  48474. }
  48475. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48476. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48477. this.beta = this.beta + (2 * Math.PI);
  48478. }
  48479. }
  48480. else {
  48481. if (this.beta > this.upperBetaLimit) {
  48482. this.beta = this.upperBetaLimit;
  48483. }
  48484. }
  48485. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48486. this.alpha = this.lowerAlphaLimit;
  48487. }
  48488. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48489. this.alpha = this.upperAlphaLimit;
  48490. }
  48491. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48492. this.radius = this.lowerRadiusLimit;
  48493. }
  48494. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48495. this.radius = this.upperRadiusLimit;
  48496. }
  48497. };
  48498. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48499. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48500. this.radius = this._computationVector.length();
  48501. if (this.radius === 0) {
  48502. this.radius = 0.0001; // Just to avoid division by zero
  48503. }
  48504. // Alpha
  48505. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48506. if (this._computationVector.z < 0) {
  48507. this.alpha = 2 * Math.PI - this.alpha;
  48508. }
  48509. // Beta
  48510. this.beta = Math.acos(this._computationVector.y / this.radius);
  48511. this._checkLimits();
  48512. };
  48513. ArcRotateCamera.prototype.setPosition = function (position) {
  48514. if (this.position.equals(position)) {
  48515. return;
  48516. }
  48517. this.position.copyFrom(position);
  48518. this.rebuildAnglesAndRadius();
  48519. };
  48520. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48521. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48522. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48523. if (target.getBoundingInfo) {
  48524. if (toBoundingCenter) {
  48525. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48526. }
  48527. else {
  48528. this._targetBoundingCenter = null;
  48529. }
  48530. this._targetHost = target;
  48531. this._target = this._getTargetPosition();
  48532. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48533. }
  48534. else {
  48535. var newTarget = target;
  48536. var currentTarget = this._getTargetPosition();
  48537. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48538. return;
  48539. }
  48540. this._targetHost = null;
  48541. this._target = newTarget;
  48542. this._targetBoundingCenter = null;
  48543. this.onMeshTargetChangedObservable.notifyObservers(null);
  48544. }
  48545. this.rebuildAnglesAndRadius();
  48546. };
  48547. ArcRotateCamera.prototype._getViewMatrix = function () {
  48548. // Compute
  48549. var cosa = Math.cos(this.alpha);
  48550. var sina = Math.sin(this.alpha);
  48551. var cosb = Math.cos(this.beta);
  48552. var sinb = Math.sin(this.beta);
  48553. if (sinb === 0) {
  48554. sinb = 0.0001;
  48555. }
  48556. var target = this._getTargetPosition();
  48557. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48558. target.addToRef(this._computationVector, this._newPosition);
  48559. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48560. if (!this._collider) {
  48561. this._collider = new BABYLON.Collider();
  48562. }
  48563. this._collider._radius = this.collisionRadius;
  48564. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48565. this._collisionTriggered = true;
  48566. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48567. }
  48568. else {
  48569. this.position.copyFrom(this._newPosition);
  48570. var up = this.upVector;
  48571. if (this.allowUpsideDown && sinb < 0) {
  48572. up = up.clone();
  48573. up = up.negate();
  48574. }
  48575. if (this.getScene().useRightHandedSystem) {
  48576. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48577. }
  48578. else {
  48579. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48580. }
  48581. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48582. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48583. }
  48584. this._currentTarget = target;
  48585. return this._viewMatrix;
  48586. };
  48587. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48588. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48589. meshes = meshes || this.getScene().meshes;
  48590. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48591. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48592. this.radius = distance * this.zoomOnFactor;
  48593. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48594. };
  48595. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48596. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48597. var meshesOrMinMaxVector;
  48598. var distance;
  48599. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48600. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48601. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48602. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48603. }
  48604. else { //minMaxVector and distance
  48605. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48606. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48607. distance = minMaxVectorAndDistance.distance;
  48608. }
  48609. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48610. if (!doNotUpdateMaxZ) {
  48611. this.maxZ = distance * 2;
  48612. }
  48613. };
  48614. /**
  48615. * @override
  48616. * Override Camera.createRigCamera
  48617. */
  48618. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48619. var alphaShift = 0;
  48620. switch (this.cameraRigMode) {
  48621. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48622. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48623. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48624. case BABYLON.Camera.RIG_MODE_VR:
  48625. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48626. break;
  48627. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48628. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48629. break;
  48630. }
  48631. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48632. rigCam._cameraRigParams = {};
  48633. return rigCam;
  48634. };
  48635. /**
  48636. * @override
  48637. * Override Camera._updateRigCameras
  48638. */
  48639. ArcRotateCamera.prototype._updateRigCameras = function () {
  48640. var camLeft = this._rigCameras[0];
  48641. var camRight = this._rigCameras[1];
  48642. camLeft.beta = camRight.beta = this.beta;
  48643. camLeft.radius = camRight.radius = this.radius;
  48644. switch (this.cameraRigMode) {
  48645. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48646. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48647. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48648. case BABYLON.Camera.RIG_MODE_VR:
  48649. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48650. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48651. break;
  48652. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48653. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48654. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48655. break;
  48656. }
  48657. _super.prototype._updateRigCameras.call(this);
  48658. };
  48659. ArcRotateCamera.prototype.dispose = function () {
  48660. this.inputs.clear();
  48661. _super.prototype.dispose.call(this);
  48662. };
  48663. ArcRotateCamera.prototype.getClassName = function () {
  48664. return "ArcRotateCamera";
  48665. };
  48666. __decorate([
  48667. BABYLON.serialize()
  48668. ], ArcRotateCamera.prototype, "alpha", void 0);
  48669. __decorate([
  48670. BABYLON.serialize()
  48671. ], ArcRotateCamera.prototype, "beta", void 0);
  48672. __decorate([
  48673. BABYLON.serialize()
  48674. ], ArcRotateCamera.prototype, "radius", void 0);
  48675. __decorate([
  48676. BABYLON.serializeAsVector3("target")
  48677. ], ArcRotateCamera.prototype, "_target", void 0);
  48678. __decorate([
  48679. BABYLON.serialize()
  48680. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48681. __decorate([
  48682. BABYLON.serialize()
  48683. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48684. __decorate([
  48685. BABYLON.serialize()
  48686. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48687. __decorate([
  48688. BABYLON.serialize()
  48689. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48690. __decorate([
  48691. BABYLON.serialize()
  48692. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48693. __decorate([
  48694. BABYLON.serialize()
  48695. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48696. __decorate([
  48697. BABYLON.serialize()
  48698. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48699. __decorate([
  48700. BABYLON.serialize()
  48701. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48702. __decorate([
  48703. BABYLON.serialize()
  48704. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48705. __decorate([
  48706. BABYLON.serialize()
  48707. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48708. __decorate([
  48709. BABYLON.serialize()
  48710. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48711. __decorate([
  48712. BABYLON.serialize()
  48713. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48714. __decorate([
  48715. BABYLON.serialize()
  48716. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48717. __decorate([
  48718. BABYLON.serializeAsVector3()
  48719. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48720. __decorate([
  48721. BABYLON.serialize()
  48722. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48723. __decorate([
  48724. BABYLON.serialize()
  48725. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48726. __decorate([
  48727. BABYLON.serialize()
  48728. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48729. return ArcRotateCamera;
  48730. }(BABYLON.TargetCamera));
  48731. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48732. })(BABYLON || (BABYLON = {}));
  48733. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48734. var BABYLON;
  48735. (function (BABYLON) {
  48736. /**
  48737. * The HemisphericLight simulates the ambient environment light,
  48738. * so the passed direction is the light reflection direction, not the incoming direction.
  48739. */
  48740. var HemisphericLight = /** @class */ (function (_super) {
  48741. __extends(HemisphericLight, _super);
  48742. /**
  48743. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48744. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48745. * The HemisphericLight can't cast shadows.
  48746. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48747. * @param name The friendly name of the light
  48748. * @param direction The direction of the light reflection
  48749. * @param scene The scene the light belongs to
  48750. */
  48751. function HemisphericLight(name, direction, scene) {
  48752. var _this = _super.call(this, name, scene) || this;
  48753. /**
  48754. * The groundColor is the light in the opposite direction to the one specified during creation.
  48755. * 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.
  48756. */
  48757. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48758. _this.direction = direction || BABYLON.Vector3.Up();
  48759. return _this;
  48760. }
  48761. HemisphericLight.prototype._buildUniformLayout = function () {
  48762. this._uniformBuffer.addUniform("vLightData", 4);
  48763. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48764. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48765. this._uniformBuffer.addUniform("vLightGround", 3);
  48766. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48767. this._uniformBuffer.addUniform("depthValues", 2);
  48768. this._uniformBuffer.create();
  48769. };
  48770. /**
  48771. * Returns the string "HemisphericLight".
  48772. * @return The class name
  48773. */
  48774. HemisphericLight.prototype.getClassName = function () {
  48775. return "HemisphericLight";
  48776. };
  48777. /**
  48778. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48779. * Returns the updated direction.
  48780. * @param target The target the direction should point to
  48781. * @return The computed direction
  48782. */
  48783. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48784. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48785. return this.direction;
  48786. };
  48787. /**
  48788. * Returns the shadow generator associated to the light.
  48789. * @returns Always null for hemispheric lights because it does not support shadows.
  48790. */
  48791. HemisphericLight.prototype.getShadowGenerator = function () {
  48792. return null;
  48793. };
  48794. /**
  48795. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48796. * @param effect The effect to update
  48797. * @param lightIndex The index of the light in the effect to update
  48798. * @returns The hemispheric light
  48799. */
  48800. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48801. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48802. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48803. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48804. return this;
  48805. };
  48806. /**
  48807. * @ignore internal use only.
  48808. */
  48809. HemisphericLight.prototype._getWorldMatrix = function () {
  48810. if (!this._worldMatrix) {
  48811. this._worldMatrix = BABYLON.Matrix.Identity();
  48812. }
  48813. return this._worldMatrix;
  48814. };
  48815. /**
  48816. * Returns the integer 3.
  48817. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48818. */
  48819. HemisphericLight.prototype.getTypeID = function () {
  48820. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48821. };
  48822. __decorate([
  48823. BABYLON.serializeAsColor3()
  48824. ], HemisphericLight.prototype, "groundColor", void 0);
  48825. __decorate([
  48826. BABYLON.serializeAsVector3()
  48827. ], HemisphericLight.prototype, "direction", void 0);
  48828. return HemisphericLight;
  48829. }(BABYLON.Light));
  48830. BABYLON.HemisphericLight = HemisphericLight;
  48831. })(BABYLON || (BABYLON = {}));
  48832. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48833. var BABYLON;
  48834. (function (BABYLON) {
  48835. /**
  48836. * Base implementation IShadowLight
  48837. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48838. */
  48839. var ShadowLight = /** @class */ (function (_super) {
  48840. __extends(ShadowLight, _super);
  48841. function ShadowLight() {
  48842. var _this = _super !== null && _super.apply(this, arguments) || this;
  48843. _this._needProjectionMatrixCompute = true;
  48844. return _this;
  48845. }
  48846. ShadowLight.prototype._setPosition = function (value) {
  48847. this._position = value;
  48848. };
  48849. Object.defineProperty(ShadowLight.prototype, "position", {
  48850. /**
  48851. * Sets the position the shadow will be casted from. Also use as the light position for both
  48852. * point and spot lights.
  48853. */
  48854. get: function () {
  48855. return this._position;
  48856. },
  48857. /**
  48858. * Sets the position the shadow will be casted from. Also use as the light position for both
  48859. * point and spot lights.
  48860. */
  48861. set: function (value) {
  48862. this._setPosition(value);
  48863. },
  48864. enumerable: true,
  48865. configurable: true
  48866. });
  48867. ShadowLight.prototype._setDirection = function (value) {
  48868. this._direction = value;
  48869. };
  48870. Object.defineProperty(ShadowLight.prototype, "direction", {
  48871. /**
  48872. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48873. * Also use as the light direction on spot and directional lights.
  48874. */
  48875. get: function () {
  48876. return this._direction;
  48877. },
  48878. /**
  48879. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48880. * Also use as the light direction on spot and directional lights.
  48881. */
  48882. set: function (value) {
  48883. this._setDirection(value);
  48884. },
  48885. enumerable: true,
  48886. configurable: true
  48887. });
  48888. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48889. /**
  48890. * Gets the shadow projection clipping minimum z value.
  48891. */
  48892. get: function () {
  48893. return this._shadowMinZ;
  48894. },
  48895. /**
  48896. * Sets the shadow projection clipping minimum z value.
  48897. */
  48898. set: function (value) {
  48899. this._shadowMinZ = value;
  48900. this.forceProjectionMatrixCompute();
  48901. },
  48902. enumerable: true,
  48903. configurable: true
  48904. });
  48905. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48906. /**
  48907. * Sets the shadow projection clipping maximum z value.
  48908. */
  48909. get: function () {
  48910. return this._shadowMaxZ;
  48911. },
  48912. /**
  48913. * Gets the shadow projection clipping maximum z value.
  48914. */
  48915. set: function (value) {
  48916. this._shadowMaxZ = value;
  48917. this.forceProjectionMatrixCompute();
  48918. },
  48919. enumerable: true,
  48920. configurable: true
  48921. });
  48922. /**
  48923. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48924. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48925. */
  48926. ShadowLight.prototype.computeTransformedInformation = function () {
  48927. if (this.parent && this.parent.getWorldMatrix) {
  48928. if (!this.transformedPosition) {
  48929. this.transformedPosition = BABYLON.Vector3.Zero();
  48930. }
  48931. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48932. // In case the direction is present.
  48933. if (this.direction) {
  48934. if (!this.transformedDirection) {
  48935. this.transformedDirection = BABYLON.Vector3.Zero();
  48936. }
  48937. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48938. }
  48939. return true;
  48940. }
  48941. return false;
  48942. };
  48943. /**
  48944. * Return the depth scale used for the shadow map.
  48945. * @returns the depth scale.
  48946. */
  48947. ShadowLight.prototype.getDepthScale = function () {
  48948. return 50.0;
  48949. };
  48950. /**
  48951. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48952. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48953. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48954. */
  48955. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48956. return this.transformedDirection ? this.transformedDirection : this.direction;
  48957. };
  48958. /**
  48959. * Returns the ShadowLight absolute position in the World.
  48960. * @returns the position vector in world space
  48961. */
  48962. ShadowLight.prototype.getAbsolutePosition = function () {
  48963. return this.transformedPosition ? this.transformedPosition : this.position;
  48964. };
  48965. /**
  48966. * Sets the ShadowLight direction toward the passed target.
  48967. * @param target The point tot target in local space
  48968. * @returns the updated ShadowLight direction
  48969. */
  48970. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48971. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48972. return this.direction;
  48973. };
  48974. /**
  48975. * Returns the light rotation in euler definition.
  48976. * @returns the x y z rotation in local space.
  48977. */
  48978. ShadowLight.prototype.getRotation = function () {
  48979. this.direction.normalize();
  48980. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48981. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48982. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48983. };
  48984. /**
  48985. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48986. * @returns true if a cube texture needs to be use
  48987. */
  48988. ShadowLight.prototype.needCube = function () {
  48989. return false;
  48990. };
  48991. /**
  48992. * Detects if the projection matrix requires to be recomputed this frame.
  48993. * @returns true if it requires to be recomputed otherwise, false.
  48994. */
  48995. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48996. return this._needProjectionMatrixCompute;
  48997. };
  48998. /**
  48999. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49000. */
  49001. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49002. this._needProjectionMatrixCompute = true;
  49003. };
  49004. /**
  49005. * Get the world matrix of the sahdow lights.
  49006. * @ignore Internal Use Only
  49007. */
  49008. ShadowLight.prototype._getWorldMatrix = function () {
  49009. if (!this._worldMatrix) {
  49010. this._worldMatrix = BABYLON.Matrix.Identity();
  49011. }
  49012. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49013. return this._worldMatrix;
  49014. };
  49015. /**
  49016. * Gets the minZ used for shadow according to both the scene and the light.
  49017. * @param activeCamera The camera we are returning the min for
  49018. * @returns the depth min z
  49019. */
  49020. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49021. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49022. };
  49023. /**
  49024. * Gets the maxZ used for shadow according to both the scene and the light.
  49025. * @param activeCamera The camera we are returning the max for
  49026. * @returns the depth max z
  49027. */
  49028. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49029. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49030. };
  49031. /**
  49032. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49033. * @param matrix The materix to updated with the projection information
  49034. * @param viewMatrix The transform matrix of the light
  49035. * @param renderList The list of mesh to render in the map
  49036. * @returns The current light
  49037. */
  49038. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49039. if (this.customProjectionMatrixBuilder) {
  49040. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49041. }
  49042. else {
  49043. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49044. }
  49045. return this;
  49046. };
  49047. __decorate([
  49048. BABYLON.serializeAsVector3()
  49049. ], ShadowLight.prototype, "position", null);
  49050. __decorate([
  49051. BABYLON.serializeAsVector3()
  49052. ], ShadowLight.prototype, "direction", null);
  49053. __decorate([
  49054. BABYLON.serialize()
  49055. ], ShadowLight.prototype, "shadowMinZ", null);
  49056. __decorate([
  49057. BABYLON.serialize()
  49058. ], ShadowLight.prototype, "shadowMaxZ", null);
  49059. return ShadowLight;
  49060. }(BABYLON.Light));
  49061. BABYLON.ShadowLight = ShadowLight;
  49062. })(BABYLON || (BABYLON = {}));
  49063. //# sourceMappingURL=babylon.shadowLight.js.map
  49064. var BABYLON;
  49065. (function (BABYLON) {
  49066. /**
  49067. * A point light is a light defined by an unique point in world space.
  49068. * The light is emitted in every direction from this point.
  49069. * A good example of a point light is a standard light bulb.
  49070. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49071. */
  49072. var PointLight = /** @class */ (function (_super) {
  49073. __extends(PointLight, _super);
  49074. /**
  49075. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49076. * A PointLight emits the light in every direction.
  49077. * It can cast shadows.
  49078. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49079. * ```javascript
  49080. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49081. * ```
  49082. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49083. * @param name The light friendly name
  49084. * @param position The position of the point light in the scene
  49085. * @param scene The scene the lights belongs to
  49086. */
  49087. function PointLight(name, position, scene) {
  49088. var _this = _super.call(this, name, scene) || this;
  49089. _this._shadowAngle = Math.PI / 2;
  49090. _this.position = position;
  49091. return _this;
  49092. }
  49093. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49094. /**
  49095. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49096. * This specifies what angle the shadow will use to be created.
  49097. *
  49098. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49099. */
  49100. get: function () {
  49101. return this._shadowAngle;
  49102. },
  49103. /**
  49104. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49105. * This specifies what angle the shadow will use to be created.
  49106. *
  49107. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49108. */
  49109. set: function (value) {
  49110. this._shadowAngle = value;
  49111. this.forceProjectionMatrixCompute();
  49112. },
  49113. enumerable: true,
  49114. configurable: true
  49115. });
  49116. Object.defineProperty(PointLight.prototype, "direction", {
  49117. /**
  49118. * Gets the direction if it has been set.
  49119. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49120. */
  49121. get: function () {
  49122. return this._direction;
  49123. },
  49124. /**
  49125. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49126. */
  49127. set: function (value) {
  49128. var previousNeedCube = this.needCube();
  49129. this._direction = value;
  49130. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49131. this._shadowGenerator.recreateShadowMap();
  49132. }
  49133. },
  49134. enumerable: true,
  49135. configurable: true
  49136. });
  49137. /**
  49138. * Returns the string "PointLight"
  49139. * @returns the class name
  49140. */
  49141. PointLight.prototype.getClassName = function () {
  49142. return "PointLight";
  49143. };
  49144. /**
  49145. * Returns the integer 0.
  49146. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49147. */
  49148. PointLight.prototype.getTypeID = function () {
  49149. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49150. };
  49151. /**
  49152. * Specifies wether or not the shadowmap should be a cube texture.
  49153. * @returns true if the shadowmap needs to be a cube texture.
  49154. */
  49155. PointLight.prototype.needCube = function () {
  49156. return !this.direction;
  49157. };
  49158. /**
  49159. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49160. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49161. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49162. */
  49163. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49164. if (this.direction) {
  49165. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49166. }
  49167. else {
  49168. switch (faceIndex) {
  49169. case 0:
  49170. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49171. case 1:
  49172. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49173. case 2:
  49174. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49175. case 3:
  49176. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49177. case 4:
  49178. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49179. case 5:
  49180. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49181. }
  49182. }
  49183. return BABYLON.Vector3.Zero();
  49184. };
  49185. /**
  49186. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49187. * - fov = PI / 2
  49188. * - aspect ratio : 1.0
  49189. * - z-near and far equal to the active camera minZ and maxZ.
  49190. * Returns the PointLight.
  49191. */
  49192. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49193. var activeCamera = this.getScene().activeCamera;
  49194. if (!activeCamera) {
  49195. return;
  49196. }
  49197. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49198. };
  49199. PointLight.prototype._buildUniformLayout = function () {
  49200. this._uniformBuffer.addUniform("vLightData", 4);
  49201. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49202. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49203. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49204. this._uniformBuffer.addUniform("depthValues", 2);
  49205. this._uniformBuffer.create();
  49206. };
  49207. /**
  49208. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49209. * @param effect The effect to update
  49210. * @param lightIndex The index of the light in the effect to update
  49211. * @returns The point light
  49212. */
  49213. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49214. if (this.computeTransformedInformation()) {
  49215. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49216. return this;
  49217. }
  49218. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49219. return this;
  49220. };
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], PointLight.prototype, "shadowAngle", null);
  49224. return PointLight;
  49225. }(BABYLON.ShadowLight));
  49226. BABYLON.PointLight = PointLight;
  49227. })(BABYLON || (BABYLON = {}));
  49228. //# sourceMappingURL=babylon.pointLight.js.map
  49229. var BABYLON;
  49230. (function (BABYLON) {
  49231. /**
  49232. * A directional light is defined by a direction (what a surprise!).
  49233. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49234. * 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.
  49235. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49236. */
  49237. var DirectionalLight = /** @class */ (function (_super) {
  49238. __extends(DirectionalLight, _super);
  49239. /**
  49240. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49241. * The directional light is emitted from everywhere in the given direction.
  49242. * It can cast shawdows.
  49243. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49244. * @param name The friendly name of the light
  49245. * @param direction The direction of the light
  49246. * @param scene The scene the light belongs to
  49247. */
  49248. function DirectionalLight(name, direction, scene) {
  49249. var _this = _super.call(this, name, scene) || this;
  49250. _this._shadowFrustumSize = 0;
  49251. _this._shadowOrthoScale = 0.1;
  49252. /**
  49253. * Automatically compute the projection matrix to best fit (including all the casters)
  49254. * on each frame.
  49255. */
  49256. _this.autoUpdateExtends = true;
  49257. // Cache
  49258. _this._orthoLeft = Number.MAX_VALUE;
  49259. _this._orthoRight = Number.MIN_VALUE;
  49260. _this._orthoTop = Number.MIN_VALUE;
  49261. _this._orthoBottom = Number.MAX_VALUE;
  49262. _this.position = direction.scale(-1.0);
  49263. _this.direction = direction;
  49264. return _this;
  49265. }
  49266. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49267. /**
  49268. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49269. */
  49270. get: function () {
  49271. return this._shadowFrustumSize;
  49272. },
  49273. /**
  49274. * Specifies a fix frustum size for the shadow generation.
  49275. */
  49276. set: function (value) {
  49277. this._shadowFrustumSize = value;
  49278. this.forceProjectionMatrixCompute();
  49279. },
  49280. enumerable: true,
  49281. configurable: true
  49282. });
  49283. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49284. /**
  49285. * Gets the shadow projection scale against the optimal computed one.
  49286. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49287. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49288. */
  49289. get: function () {
  49290. return this._shadowOrthoScale;
  49291. },
  49292. /**
  49293. * Sets the shadow projection scale against the optimal computed one.
  49294. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49295. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49296. */
  49297. set: function (value) {
  49298. this._shadowOrthoScale = value;
  49299. this.forceProjectionMatrixCompute();
  49300. },
  49301. enumerable: true,
  49302. configurable: true
  49303. });
  49304. /**
  49305. * Returns the string "DirectionalLight".
  49306. * @return The class name
  49307. */
  49308. DirectionalLight.prototype.getClassName = function () {
  49309. return "DirectionalLight";
  49310. };
  49311. /**
  49312. * Returns the integer 1.
  49313. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49314. */
  49315. DirectionalLight.prototype.getTypeID = function () {
  49316. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49317. };
  49318. /**
  49319. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49320. * Returns the DirectionalLight Shadow projection matrix.
  49321. */
  49322. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49323. if (this.shadowFrustumSize > 0) {
  49324. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49325. }
  49326. else {
  49327. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49328. }
  49329. };
  49330. /**
  49331. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49332. * Returns the DirectionalLight Shadow projection matrix.
  49333. */
  49334. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49335. var activeCamera = this.getScene().activeCamera;
  49336. if (!activeCamera) {
  49337. return;
  49338. }
  49339. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49340. };
  49341. /**
  49342. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49343. * Returns the DirectionalLight Shadow projection matrix.
  49344. */
  49345. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49346. var activeCamera = this.getScene().activeCamera;
  49347. if (!activeCamera) {
  49348. return;
  49349. }
  49350. // Check extends
  49351. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49352. var tempVector3 = BABYLON.Vector3.Zero();
  49353. this._orthoLeft = Number.MAX_VALUE;
  49354. this._orthoRight = Number.MIN_VALUE;
  49355. this._orthoTop = Number.MIN_VALUE;
  49356. this._orthoBottom = Number.MAX_VALUE;
  49357. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49358. var mesh = renderList[meshIndex];
  49359. if (!mesh) {
  49360. continue;
  49361. }
  49362. var boundingInfo = mesh.getBoundingInfo();
  49363. var boundingBox = boundingInfo.boundingBox;
  49364. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49365. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49366. if (tempVector3.x < this._orthoLeft)
  49367. this._orthoLeft = tempVector3.x;
  49368. if (tempVector3.y < this._orthoBottom)
  49369. this._orthoBottom = tempVector3.y;
  49370. if (tempVector3.x > this._orthoRight)
  49371. this._orthoRight = tempVector3.x;
  49372. if (tempVector3.y > this._orthoTop)
  49373. this._orthoTop = tempVector3.y;
  49374. }
  49375. }
  49376. }
  49377. var xOffset = this._orthoRight - this._orthoLeft;
  49378. var yOffset = this._orthoTop - this._orthoBottom;
  49379. 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);
  49380. };
  49381. DirectionalLight.prototype._buildUniformLayout = function () {
  49382. this._uniformBuffer.addUniform("vLightData", 4);
  49383. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49384. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49385. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49386. this._uniformBuffer.addUniform("depthValues", 2);
  49387. this._uniformBuffer.create();
  49388. };
  49389. /**
  49390. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49391. * @param effect The effect to update
  49392. * @param lightIndex The index of the light in the effect to update
  49393. * @returns The directional light
  49394. */
  49395. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49396. if (this.computeTransformedInformation()) {
  49397. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49398. return this;
  49399. }
  49400. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49401. return this;
  49402. };
  49403. /**
  49404. * Gets the minZ used for shadow according to both the scene and the light.
  49405. *
  49406. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49407. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49408. * @param activeCamera The camera we are returning the min for
  49409. * @returns the depth min z
  49410. */
  49411. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49412. return 1;
  49413. };
  49414. /**
  49415. * Gets the maxZ used for shadow according to both the scene and the light.
  49416. *
  49417. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49418. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49419. * @param activeCamera The camera we are returning the max for
  49420. * @returns the depth max z
  49421. */
  49422. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49423. return 1;
  49424. };
  49425. __decorate([
  49426. BABYLON.serialize()
  49427. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49428. __decorate([
  49429. BABYLON.serialize()
  49430. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49431. __decorate([
  49432. BABYLON.serialize()
  49433. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49434. return DirectionalLight;
  49435. }(BABYLON.ShadowLight));
  49436. BABYLON.DirectionalLight = DirectionalLight;
  49437. })(BABYLON || (BABYLON = {}));
  49438. //# sourceMappingURL=babylon.directionalLight.js.map
  49439. var BABYLON;
  49440. (function (BABYLON) {
  49441. /**
  49442. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49443. * These values define a cone of light starting from the position, emitting toward the direction.
  49444. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49445. * and the exponent defines the speed of the decay of the light with distance (reach).
  49446. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49447. */
  49448. var SpotLight = /** @class */ (function (_super) {
  49449. __extends(SpotLight, _super);
  49450. /**
  49451. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49452. * It can cast shadows.
  49453. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49454. * @param name The light friendly name
  49455. * @param position The position of the spot light in the scene
  49456. * @param direction The direction of the light in the scene
  49457. * @param angle The cone angle of the light in Radians
  49458. * @param exponent The light decay speed with the distance from the emission spot
  49459. * @param scene The scene the lights belongs to
  49460. */
  49461. function SpotLight(name, position, direction, angle, exponent, scene) {
  49462. var _this = _super.call(this, name, scene) || this;
  49463. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49464. _this._projectionTextureLightNear = 1e-6;
  49465. _this._projectionTextureLightFar = 1000.0;
  49466. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49467. _this._projectionTextureViewLightDirty = true;
  49468. _this._projectionTextureProjectionLightDirty = true;
  49469. _this._projectionTextureDirty = true;
  49470. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49471. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49472. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49473. _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);
  49474. _this.position = position;
  49475. _this.direction = direction;
  49476. _this.angle = angle;
  49477. _this.exponent = exponent;
  49478. return _this;
  49479. }
  49480. Object.defineProperty(SpotLight.prototype, "angle", {
  49481. /**
  49482. * Gets the cone angle of the spot light in Radians.
  49483. */
  49484. get: function () {
  49485. return this._angle;
  49486. },
  49487. /**
  49488. * Sets the cone angle of the spot light in Radians.
  49489. */
  49490. set: function (value) {
  49491. this._angle = value;
  49492. this._projectionTextureProjectionLightDirty = true;
  49493. this.forceProjectionMatrixCompute();
  49494. },
  49495. enumerable: true,
  49496. configurable: true
  49497. });
  49498. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49499. /**
  49500. * Allows scaling the angle of the light for shadow generation only.
  49501. */
  49502. get: function () {
  49503. return this._shadowAngleScale;
  49504. },
  49505. /**
  49506. * Allows scaling the angle of the light for shadow generation only.
  49507. */
  49508. set: function (value) {
  49509. this._shadowAngleScale = value;
  49510. this.forceProjectionMatrixCompute();
  49511. },
  49512. enumerable: true,
  49513. configurable: true
  49514. });
  49515. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49516. /**
  49517. * Allows reading the projecton texture
  49518. */
  49519. get: function () {
  49520. return this._projectionTextureMatrix;
  49521. },
  49522. enumerable: true,
  49523. configurable: true
  49524. });
  49525. ;
  49526. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49527. /**
  49528. * Gets the near clip of the Spotlight for texture projection.
  49529. */
  49530. get: function () {
  49531. return this._projectionTextureLightNear;
  49532. },
  49533. /**
  49534. * Sets the near clip of the Spotlight for texture projection.
  49535. */
  49536. set: function (value) {
  49537. this._projectionTextureLightNear = value;
  49538. this._projectionTextureProjectionLightDirty = true;
  49539. },
  49540. enumerable: true,
  49541. configurable: true
  49542. });
  49543. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49544. /**
  49545. * Gets the far clip of the Spotlight for texture projection.
  49546. */
  49547. get: function () {
  49548. return this._projectionTextureLightFar;
  49549. },
  49550. /**
  49551. * Sets the far clip of the Spotlight for texture projection.
  49552. */
  49553. set: function (value) {
  49554. this._projectionTextureLightFar = value;
  49555. this._projectionTextureProjectionLightDirty = true;
  49556. },
  49557. enumerable: true,
  49558. configurable: true
  49559. });
  49560. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49561. /**
  49562. * Gets the Up vector of the Spotlight for texture projection.
  49563. */
  49564. get: function () {
  49565. return this._projectionTextureUpDirection;
  49566. },
  49567. /**
  49568. * Sets the Up vector of the Spotlight for texture projection.
  49569. */
  49570. set: function (value) {
  49571. this._projectionTextureUpDirection = value;
  49572. this._projectionTextureProjectionLightDirty = true;
  49573. },
  49574. enumerable: true,
  49575. configurable: true
  49576. });
  49577. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49578. /**
  49579. * Gets the projection texture of the light.
  49580. */
  49581. get: function () {
  49582. return this._projectionTexture;
  49583. },
  49584. /**
  49585. * Sets the projection texture of the light.
  49586. */
  49587. set: function (value) {
  49588. this._projectionTexture = value;
  49589. this._projectionTextureDirty = true;
  49590. },
  49591. enumerable: true,
  49592. configurable: true
  49593. });
  49594. /**
  49595. * Returns the string "SpotLight".
  49596. * @returns the class name
  49597. */
  49598. SpotLight.prototype.getClassName = function () {
  49599. return "SpotLight";
  49600. };
  49601. /**
  49602. * Returns the integer 2.
  49603. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49604. */
  49605. SpotLight.prototype.getTypeID = function () {
  49606. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49607. };
  49608. /**
  49609. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49610. */
  49611. SpotLight.prototype._setDirection = function (value) {
  49612. _super.prototype._setDirection.call(this, value);
  49613. this._projectionTextureViewLightDirty = true;
  49614. };
  49615. /**
  49616. * Overrides the position setter to recompute the projection texture view light Matrix.
  49617. */
  49618. SpotLight.prototype._setPosition = function (value) {
  49619. _super.prototype._setPosition.call(this, value);
  49620. this._projectionTextureViewLightDirty = true;
  49621. };
  49622. /**
  49623. * 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.
  49624. * Returns the SpotLight.
  49625. */
  49626. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49627. var activeCamera = this.getScene().activeCamera;
  49628. if (!activeCamera) {
  49629. return;
  49630. }
  49631. this._shadowAngleScale = this._shadowAngleScale || 1;
  49632. var angle = this._shadowAngleScale * this._angle;
  49633. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49634. };
  49635. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49636. this._projectionTextureViewLightDirty = false;
  49637. this._projectionTextureDirty = true;
  49638. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49639. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49640. };
  49641. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49642. this._projectionTextureProjectionLightDirty = false;
  49643. this._projectionTextureDirty = true;
  49644. var light_far = this.projectionTextureLightFar;
  49645. var light_near = this.projectionTextureLightNear;
  49646. var P = light_far / (light_far - light_near);
  49647. var Q = -P * light_near;
  49648. var S = 1.0 / Math.tan(this._angle / 2.0);
  49649. var A = 1.0;
  49650. 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);
  49651. };
  49652. /**
  49653. * Main function for light texture projection matrix computing.
  49654. */
  49655. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49656. this._projectionTextureDirty = false;
  49657. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49658. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49659. };
  49660. SpotLight.prototype._buildUniformLayout = function () {
  49661. this._uniformBuffer.addUniform("vLightData", 4);
  49662. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49663. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49664. this._uniformBuffer.addUniform("vLightDirection", 3);
  49665. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49666. this._uniformBuffer.addUniform("depthValues", 2);
  49667. this._uniformBuffer.create();
  49668. };
  49669. /**
  49670. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49671. * @param effect The effect to update
  49672. * @param lightIndex The index of the light in the effect to update
  49673. * @returns The spot light
  49674. */
  49675. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49676. var normalizeDirection;
  49677. if (this.computeTransformedInformation()) {
  49678. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49679. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49680. }
  49681. else {
  49682. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49683. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49684. }
  49685. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49686. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49687. if (this._projectionTextureViewLightDirty) {
  49688. this._computeProjectionTextureViewLightMatrix();
  49689. }
  49690. if (this._projectionTextureProjectionLightDirty) {
  49691. this._computeProjectionTextureProjectionLightMatrix();
  49692. }
  49693. if (this._projectionTextureDirty) {
  49694. this._computeProjectionTextureMatrix();
  49695. }
  49696. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49697. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49698. }
  49699. return this;
  49700. };
  49701. /**
  49702. * Disposes the light and the associated resources.
  49703. */
  49704. SpotLight.prototype.dispose = function () {
  49705. _super.prototype.dispose.call(this);
  49706. if (this._projectionTexture) {
  49707. this._projectionTexture.dispose();
  49708. }
  49709. };
  49710. __decorate([
  49711. BABYLON.serialize()
  49712. ], SpotLight.prototype, "angle", null);
  49713. __decorate([
  49714. BABYLON.serialize()
  49715. ], SpotLight.prototype, "shadowAngleScale", null);
  49716. __decorate([
  49717. BABYLON.serialize()
  49718. ], SpotLight.prototype, "exponent", void 0);
  49719. __decorate([
  49720. BABYLON.serialize()
  49721. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49722. __decorate([
  49723. BABYLON.serialize()
  49724. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49725. __decorate([
  49726. BABYLON.serialize()
  49727. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49728. __decorate([
  49729. BABYLON.serializeAsTexture("projectedLightTexture")
  49730. ], SpotLight.prototype, "_projectionTexture", void 0);
  49731. return SpotLight;
  49732. }(BABYLON.ShadowLight));
  49733. BABYLON.SpotLight = SpotLight;
  49734. })(BABYLON || (BABYLON = {}));
  49735. //# sourceMappingURL=babylon.spotLight.js.map
  49736. var BABYLON;
  49737. (function (BABYLON) {
  49738. /**
  49739. * Class used to override all child animations of a given target
  49740. */
  49741. var AnimationPropertiesOverride = /** @class */ (function () {
  49742. function AnimationPropertiesOverride() {
  49743. /**
  49744. * Gets or sets a value indicating if animation blending must be used
  49745. */
  49746. this.enableBlending = false;
  49747. /**
  49748. * Gets or sets the blending speed to use when enableBlending is true
  49749. */
  49750. this.blendingSpeed = 0.01;
  49751. /**
  49752. * Gets or sets the default loop mode to use
  49753. */
  49754. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49755. }
  49756. return AnimationPropertiesOverride;
  49757. }());
  49758. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49759. })(BABYLON || (BABYLON = {}));
  49760. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49761. var BABYLON;
  49762. (function (BABYLON) {
  49763. /**
  49764. * Represents the range of an animation
  49765. */
  49766. var AnimationRange = /** @class */ (function () {
  49767. /**
  49768. * Initializes the range of an animation
  49769. * @param name The name of the animation range
  49770. * @param from The starting frame of the animation
  49771. * @param to The ending frame of the animation
  49772. */
  49773. function AnimationRange(
  49774. /**The name of the animation range**/
  49775. name,
  49776. /**The starting frame of the animation */
  49777. from,
  49778. /**The ending frame of the animation*/
  49779. to) {
  49780. this.name = name;
  49781. this.from = from;
  49782. this.to = to;
  49783. }
  49784. /**
  49785. * Makes a copy of the animation range
  49786. * @returns A copy of the animation range
  49787. */
  49788. AnimationRange.prototype.clone = function () {
  49789. return new AnimationRange(this.name, this.from, this.to);
  49790. };
  49791. return AnimationRange;
  49792. }());
  49793. BABYLON.AnimationRange = AnimationRange;
  49794. /**
  49795. * Composed of a frame, and an action function
  49796. */
  49797. var AnimationEvent = /** @class */ (function () {
  49798. /**
  49799. * Initializes the animation event
  49800. * @param frame The frame for which the event is triggered
  49801. * @param action The event to perform when triggered
  49802. * @param onlyOnce Specifies if the event should be triggered only once
  49803. */
  49804. function AnimationEvent(
  49805. /** The frame for which the event is triggered **/
  49806. frame,
  49807. /** The event to perform when triggered **/
  49808. action,
  49809. /** Specifies if the event should be triggered only once**/
  49810. onlyOnce) {
  49811. this.frame = frame;
  49812. this.action = action;
  49813. this.onlyOnce = onlyOnce;
  49814. /**
  49815. * Specifies if the animation event is done
  49816. */
  49817. this.isDone = false;
  49818. }
  49819. return AnimationEvent;
  49820. }());
  49821. BABYLON.AnimationEvent = AnimationEvent;
  49822. /**
  49823. * A cursor which tracks a point on a path
  49824. */
  49825. var PathCursor = /** @class */ (function () {
  49826. /**
  49827. * Initializes the path cursor
  49828. * @param path The path to track
  49829. */
  49830. function PathCursor(path) {
  49831. this.path = path;
  49832. /**
  49833. * Stores path cursor callbacks for when an onchange event is triggered
  49834. */
  49835. this._onchange = new Array();
  49836. /**
  49837. * The value of the path cursor
  49838. */
  49839. this.value = 0;
  49840. /**
  49841. * The animation array of the path cursor
  49842. */
  49843. this.animations = new Array();
  49844. }
  49845. /**
  49846. * Gets the cursor point on the path
  49847. * @returns A point on the path cursor at the cursor location
  49848. */
  49849. PathCursor.prototype.getPoint = function () {
  49850. var point = this.path.getPointAtLengthPosition(this.value);
  49851. return new BABYLON.Vector3(point.x, 0, point.y);
  49852. };
  49853. /**
  49854. * Moves the cursor ahead by the step amount
  49855. * @param step The amount to move the cursor forward
  49856. * @returns This path cursor
  49857. */
  49858. PathCursor.prototype.moveAhead = function (step) {
  49859. if (step === void 0) { step = 0.002; }
  49860. this.move(step);
  49861. return this;
  49862. };
  49863. /**
  49864. * Moves the cursor behind by the step amount
  49865. * @param step The amount to move the cursor back
  49866. * @returns This path cursor
  49867. */
  49868. PathCursor.prototype.moveBack = function (step) {
  49869. if (step === void 0) { step = 0.002; }
  49870. this.move(-step);
  49871. return this;
  49872. };
  49873. /**
  49874. * Moves the cursor by the step amount
  49875. * If the step amount is greater than one, an exception is thrown
  49876. * @param step The amount to move the cursor
  49877. * @returns This path cursor
  49878. */
  49879. PathCursor.prototype.move = function (step) {
  49880. if (Math.abs(step) > 1) {
  49881. throw "step size should be less than 1.";
  49882. }
  49883. this.value += step;
  49884. this.ensureLimits();
  49885. this.raiseOnChange();
  49886. return this;
  49887. };
  49888. /**
  49889. * Ensures that the value is limited between zero and one
  49890. * @returns This path cursor
  49891. */
  49892. PathCursor.prototype.ensureLimits = function () {
  49893. while (this.value > 1) {
  49894. this.value -= 1;
  49895. }
  49896. while (this.value < 0) {
  49897. this.value += 1;
  49898. }
  49899. return this;
  49900. };
  49901. /**
  49902. * Runs onchange callbacks on change (used by the animation engine)
  49903. * @returns This path cursor
  49904. */
  49905. PathCursor.prototype.raiseOnChange = function () {
  49906. var _this = this;
  49907. this._onchange.forEach(function (f) { return f(_this); });
  49908. return this;
  49909. };
  49910. /**
  49911. * Executes a function on change
  49912. * @param f A path cursor onchange callback
  49913. * @returns This path cursor
  49914. */
  49915. PathCursor.prototype.onchange = function (f) {
  49916. this._onchange.push(f);
  49917. return this;
  49918. };
  49919. return PathCursor;
  49920. }());
  49921. BABYLON.PathCursor = PathCursor;
  49922. /**
  49923. * Enum for the animation key frame interpolation type
  49924. */
  49925. var AnimationKeyInterpolation;
  49926. (function (AnimationKeyInterpolation) {
  49927. /**
  49928. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49929. */
  49930. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49931. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49932. /**
  49933. * Class used to store any kind of animation
  49934. */
  49935. var Animation = /** @class */ (function () {
  49936. /**
  49937. * Initializes the animation
  49938. * @param name Name of the animation
  49939. * @param targetProperty Property to animate
  49940. * @param framePerSecond The frames per second of the animation
  49941. * @param dataType The data type of the animation
  49942. * @param loopMode The loop mode of the animation
  49943. * @param enableBlendings Specifies if blending should be enabled
  49944. */
  49945. function Animation(
  49946. /**Name of the animation */
  49947. name,
  49948. /**Property to animate */
  49949. targetProperty,
  49950. /**The frames per second of the animation */
  49951. framePerSecond,
  49952. /**The data type of the animation */
  49953. dataType,
  49954. /**The loop mode of the animation */
  49955. loopMode,
  49956. /**Specifies if blending should be enabled */
  49957. enableBlending) {
  49958. this.name = name;
  49959. this.targetProperty = targetProperty;
  49960. this.framePerSecond = framePerSecond;
  49961. this.dataType = dataType;
  49962. this.loopMode = loopMode;
  49963. this.enableBlending = enableBlending;
  49964. /**
  49965. * @ignore Internal use only
  49966. */
  49967. this._runtimeAnimations = new Array();
  49968. /**
  49969. * The set of event that will be linked to this animation
  49970. */
  49971. this._events = new Array();
  49972. /**
  49973. * Stores the blending speed of the animation
  49974. */
  49975. this.blendingSpeed = 0.01;
  49976. /**
  49977. * Stores the animation ranges for the animation
  49978. */
  49979. this._ranges = {};
  49980. this.targetPropertyPath = targetProperty.split(".");
  49981. this.dataType = dataType;
  49982. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49983. }
  49984. /**
  49985. * @ignore Internal use
  49986. */
  49987. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49988. var dataType = undefined;
  49989. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49990. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49991. }
  49992. else if (from instanceof BABYLON.Quaternion) {
  49993. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49994. }
  49995. else if (from instanceof BABYLON.Vector3) {
  49996. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49997. }
  49998. else if (from instanceof BABYLON.Vector2) {
  49999. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50000. }
  50001. else if (from instanceof BABYLON.Color3) {
  50002. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50003. }
  50004. else if (from instanceof BABYLON.Size) {
  50005. dataType = Animation.ANIMATIONTYPE_SIZE;
  50006. }
  50007. if (dataType == undefined) {
  50008. return null;
  50009. }
  50010. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50011. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50012. animation.setKeys(keys);
  50013. if (easingFunction !== undefined) {
  50014. animation.setEasingFunction(easingFunction);
  50015. }
  50016. return animation;
  50017. };
  50018. /**
  50019. * Sets up an animation
  50020. * @param property The property to animate
  50021. * @param animationType The animation type to apply
  50022. * @param framePerSecond The frames per second of the animation
  50023. * @param easingFunction The easing function used in the animation
  50024. * @returns The created animation
  50025. */
  50026. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50027. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50028. animation.setEasingFunction(easingFunction);
  50029. return animation;
  50030. };
  50031. /**
  50032. * Create and start an animation on a node
  50033. * @param name defines the name of the global animation that will be run on all nodes
  50034. * @param node defines the root node where the animation will take place
  50035. * @param targetProperty defines property to animate
  50036. * @param framePerSecond defines the number of frame per second yo use
  50037. * @param totalFrame defines the number of frames in total
  50038. * @param from defines the initial value
  50039. * @param to defines the final value
  50040. * @param loopMode defines which loop mode you want to use (off by default)
  50041. * @param easingFunction defines the easing function to use (linear by default)
  50042. * @param onAnimationEnd defines the callback to call when animation end
  50043. * @returns the animatable created for this animation
  50044. */
  50045. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50046. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50047. if (!animation) {
  50048. return null;
  50049. }
  50050. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50051. };
  50052. /**
  50053. * Create and start an animation on a node and its descendants
  50054. * @param name defines the name of the global animation that will be run on all nodes
  50055. * @param node defines the root node where the animation will take place
  50056. * @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
  50057. * @param targetProperty defines property to animate
  50058. * @param framePerSecond defines the number of frame per second to use
  50059. * @param totalFrame defines the number of frames in total
  50060. * @param from defines the initial value
  50061. * @param to defines the final value
  50062. * @param loopMode defines which loop mode you want to use (off by default)
  50063. * @param easingFunction defines the easing function to use (linear by default)
  50064. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50065. * @returns the list of animatables created for all nodes
  50066. * @example https://www.babylonjs-playground.com/#MH0VLI
  50067. */
  50068. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50069. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50070. if (!animation) {
  50071. return null;
  50072. }
  50073. var scene = node.getScene();
  50074. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50075. };
  50076. /**
  50077. * Creates a new animation, merges it with the existing animations and starts it
  50078. * @param name Name of the animation
  50079. * @param node Node which contains the scene that begins the animations
  50080. * @param targetProperty Specifies which property to animate
  50081. * @param framePerSecond The frames per second of the animation
  50082. * @param totalFrame The total number of frames
  50083. * @param from The frame at the beginning of the animation
  50084. * @param to The frame at the end of the animation
  50085. * @param loopMode Specifies the loop mode of the animation
  50086. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50087. * @param onAnimationEnd Callback to run once the animation is complete
  50088. * @returns Nullable animation
  50089. */
  50090. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50091. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50092. if (!animation) {
  50093. return null;
  50094. }
  50095. node.animations.push(animation);
  50096. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50097. };
  50098. /**
  50099. * Transition property of the Camera to the target Value
  50100. * @param property The property to transition
  50101. * @param targetValue The target Value of the property
  50102. * @param host The object where the property to animate belongs
  50103. * @param scene Scene used to run the animation
  50104. * @param frameRate Framerate (in frame/s) to use
  50105. * @param transition The transition type we want to use
  50106. * @param duration The duration of the animation, in milliseconds
  50107. * @param onAnimationEnd Callback trigger at the end of the animation
  50108. * @returns Nullable animation
  50109. */
  50110. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50111. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50112. if (duration <= 0) {
  50113. host[property] = targetValue;
  50114. if (onAnimationEnd) {
  50115. onAnimationEnd();
  50116. }
  50117. return null;
  50118. }
  50119. var endFrame = frameRate * (duration / 1000);
  50120. transition.setKeys([{
  50121. frame: 0,
  50122. value: host[property].clone ? host[property].clone() : host[property]
  50123. },
  50124. {
  50125. frame: endFrame,
  50126. value: targetValue
  50127. }]);
  50128. if (!host.animations) {
  50129. host.animations = [];
  50130. }
  50131. host.animations.push(transition);
  50132. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50133. animation.onAnimationEnd = onAnimationEnd;
  50134. return animation;
  50135. };
  50136. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50137. /**
  50138. * Return the array of runtime animations currently using this animation
  50139. */
  50140. get: function () {
  50141. return this._runtimeAnimations;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50147. /**
  50148. * Specifies if any of the runtime animations are currently running
  50149. */
  50150. get: function () {
  50151. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50152. var runtimeAnimation = _a[_i];
  50153. if (!runtimeAnimation.isStopped) {
  50154. return true;
  50155. }
  50156. }
  50157. return false;
  50158. },
  50159. enumerable: true,
  50160. configurable: true
  50161. });
  50162. // Methods
  50163. /**
  50164. * Converts the animation to a string
  50165. * @param fullDetails support for multiple levels of logging within scene loading
  50166. * @returns String form of the animation
  50167. */
  50168. Animation.prototype.toString = function (fullDetails) {
  50169. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50170. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50171. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50172. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50173. if (fullDetails) {
  50174. ret += ", Ranges: {";
  50175. var first = true;
  50176. for (var name in this._ranges) {
  50177. if (first) {
  50178. ret += ", ";
  50179. first = false;
  50180. }
  50181. ret += name;
  50182. }
  50183. ret += "}";
  50184. }
  50185. return ret;
  50186. };
  50187. /**
  50188. * Add an event to this animation
  50189. * @param event Event to add
  50190. */
  50191. Animation.prototype.addEvent = function (event) {
  50192. this._events.push(event);
  50193. };
  50194. /**
  50195. * Remove all events found at the given frame
  50196. * @param frame The frame to remove events from
  50197. */
  50198. Animation.prototype.removeEvents = function (frame) {
  50199. for (var index = 0; index < this._events.length; index++) {
  50200. if (this._events[index].frame === frame) {
  50201. this._events.splice(index, 1);
  50202. index--;
  50203. }
  50204. }
  50205. };
  50206. /**
  50207. * Retrieves all the events from the animation
  50208. * @returns Events from the animation
  50209. */
  50210. Animation.prototype.getEvents = function () {
  50211. return this._events;
  50212. };
  50213. /**
  50214. * Creates an animation range
  50215. * @param name Name of the animation range
  50216. * @param from Starting frame of the animation range
  50217. * @param to Ending frame of the animation
  50218. */
  50219. Animation.prototype.createRange = function (name, from, to) {
  50220. // check name not already in use; could happen for bones after serialized
  50221. if (!this._ranges[name]) {
  50222. this._ranges[name] = new AnimationRange(name, from, to);
  50223. }
  50224. };
  50225. /**
  50226. * Deletes an animation range by name
  50227. * @param name Name of the animation range to delete
  50228. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50229. */
  50230. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50231. if (deleteFrames === void 0) { deleteFrames = true; }
  50232. var range = this._ranges[name];
  50233. if (!range) {
  50234. return;
  50235. }
  50236. if (deleteFrames) {
  50237. var from = range.from;
  50238. var to = range.to;
  50239. // this loop MUST go high to low for multiple splices to work
  50240. for (var key = this._keys.length - 1; key >= 0; key--) {
  50241. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50242. this._keys.splice(key, 1);
  50243. }
  50244. }
  50245. }
  50246. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50247. };
  50248. /**
  50249. * Gets the animation range by name, or null if not defined
  50250. * @param name Name of the animation range
  50251. * @returns Nullable animation range
  50252. */
  50253. Animation.prototype.getRange = function (name) {
  50254. return this._ranges[name];
  50255. };
  50256. /**
  50257. * Gets the key frames from the animation
  50258. * @returns The key frames of the animation
  50259. */
  50260. Animation.prototype.getKeys = function () {
  50261. return this._keys;
  50262. };
  50263. /**
  50264. * Gets the highest frame rate of the animation
  50265. * @returns Highest frame rate of the animation
  50266. */
  50267. Animation.prototype.getHighestFrame = function () {
  50268. var ret = 0;
  50269. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50270. if (ret < this._keys[key].frame) {
  50271. ret = this._keys[key].frame;
  50272. }
  50273. }
  50274. return ret;
  50275. };
  50276. /**
  50277. * Gets the easing function of the animation
  50278. * @returns Easing function of the animation
  50279. */
  50280. Animation.prototype.getEasingFunction = function () {
  50281. return this._easingFunction;
  50282. };
  50283. /**
  50284. * Sets the easing function of the animation
  50285. * @param easingFunction A custom mathematical formula for animation
  50286. */
  50287. Animation.prototype.setEasingFunction = function (easingFunction) {
  50288. this._easingFunction = easingFunction;
  50289. };
  50290. /**
  50291. * Interpolates a scalar linearly
  50292. * @param startValue Start value of the animation curve
  50293. * @param endValue End value of the animation curve
  50294. * @param gradient Scalar amount to interpolate
  50295. * @returns Interpolated scalar value
  50296. */
  50297. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50298. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50299. };
  50300. /**
  50301. * Interpolates a scalar cubically
  50302. * @param startValue Start value of the animation curve
  50303. * @param outTangent End tangent of the animation
  50304. * @param endValue End value of the animation curve
  50305. * @param inTangent Start tangent of the animation curve
  50306. * @param gradient Scalar amount to interpolate
  50307. * @returns Interpolated scalar value
  50308. */
  50309. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50310. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50311. };
  50312. /**
  50313. * Interpolates a quaternion using a spherical linear interpolation
  50314. * @param startValue Start value of the animation curve
  50315. * @param endValue End value of the animation curve
  50316. * @param gradient Scalar amount to interpolate
  50317. * @returns Interpolated quaternion value
  50318. */
  50319. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50320. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50321. };
  50322. /**
  50323. * Interpolates a quaternion cubically
  50324. * @param startValue Start value of the animation curve
  50325. * @param outTangent End tangent of the animation curve
  50326. * @param endValue End value of the animation curve
  50327. * @param inTangent Start tangent of the animation curve
  50328. * @param gradient Scalar amount to interpolate
  50329. * @returns Interpolated quaternion value
  50330. */
  50331. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50332. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50333. };
  50334. /**
  50335. * Interpolates a Vector3 linearl
  50336. * @param startValue Start value of the animation curve
  50337. * @param endValue End value of the animation curve
  50338. * @param gradient Scalar amount to interpolate
  50339. * @returns Interpolated scalar value
  50340. */
  50341. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50342. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50343. };
  50344. /**
  50345. * Interpolates a Vector3 cubically
  50346. * @param startValue Start value of the animation curve
  50347. * @param outTangent End tangent of the animation
  50348. * @param endValue End value of the animation curve
  50349. * @param inTangent Start tangent of the animation curve
  50350. * @param gradient Scalar amount to interpolate
  50351. * @returns InterpolatedVector3 value
  50352. */
  50353. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50354. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50355. };
  50356. /**
  50357. * Interpolates a Vector2 linearly
  50358. * @param startValue Start value of the animation curve
  50359. * @param endValue End value of the animation curve
  50360. * @param gradient Scalar amount to interpolate
  50361. * @returns Interpolated Vector2 value
  50362. */
  50363. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50364. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50365. };
  50366. /**
  50367. * Interpolates a Vector2 cubically
  50368. * @param startValue Start value of the animation curve
  50369. * @param outTangent End tangent of the animation
  50370. * @param endValue End value of the animation curve
  50371. * @param inTangent Start tangent of the animation curve
  50372. * @param gradient Scalar amount to interpolate
  50373. * @returns Interpolated Vector2 value
  50374. */
  50375. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50376. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50377. };
  50378. /**
  50379. * Interpolates a size linearly
  50380. * @param startValue Start value of the animation curve
  50381. * @param endValue End value of the animation curve
  50382. * @param gradient Scalar amount to interpolate
  50383. * @returns Interpolated Size value
  50384. */
  50385. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50386. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50387. };
  50388. /**
  50389. * Interpolates a Color3 linearly
  50390. * @param startValue Start value of the animation curve
  50391. * @param endValue End value of the animation curve
  50392. * @param gradient Scalar amount to interpolate
  50393. * @returns Interpolated Color3 value
  50394. */
  50395. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50396. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50397. };
  50398. /**
  50399. * @ignore Internal use only
  50400. */
  50401. Animation.prototype._getKeyValue = function (value) {
  50402. if (typeof value === "function") {
  50403. return value();
  50404. }
  50405. return value;
  50406. };
  50407. /**
  50408. * @ignore Internal use only
  50409. */
  50410. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50411. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50412. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50413. }
  50414. var keys = this.getKeys();
  50415. // Try to get a hash to find the right key
  50416. 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));
  50417. if (keys[startKeyIndex].frame >= currentFrame) {
  50418. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50419. startKeyIndex--;
  50420. }
  50421. }
  50422. for (var key = startKeyIndex; key < keys.length; key++) {
  50423. var endKey = keys[key + 1];
  50424. if (endKey.frame >= currentFrame) {
  50425. var startKey = keys[key];
  50426. var startValue = this._getKeyValue(startKey.value);
  50427. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50428. return startValue;
  50429. }
  50430. var endValue = this._getKeyValue(endKey.value);
  50431. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50432. var frameDelta = endKey.frame - startKey.frame;
  50433. // gradient : percent of currentFrame between the frame inf and the frame sup
  50434. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50435. // check for easingFunction and correction of gradient
  50436. var easingFunction = this.getEasingFunction();
  50437. if (easingFunction != null) {
  50438. gradient = easingFunction.ease(gradient);
  50439. }
  50440. switch (this.dataType) {
  50441. // Float
  50442. case Animation.ANIMATIONTYPE_FLOAT:
  50443. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50444. switch (loopMode) {
  50445. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50446. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50447. return floatValue;
  50448. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50449. return offsetValue * repeatCount + floatValue;
  50450. }
  50451. break;
  50452. // Quaternion
  50453. case Animation.ANIMATIONTYPE_QUATERNION:
  50454. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50455. switch (loopMode) {
  50456. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50457. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50458. return quatValue;
  50459. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50460. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50461. }
  50462. return quatValue;
  50463. // Vector3
  50464. case Animation.ANIMATIONTYPE_VECTOR3:
  50465. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50466. switch (loopMode) {
  50467. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50468. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50469. return vec3Value;
  50470. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50471. return vec3Value.add(offsetValue.scale(repeatCount));
  50472. }
  50473. // Vector2
  50474. case Animation.ANIMATIONTYPE_VECTOR2:
  50475. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50476. switch (loopMode) {
  50477. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50478. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50479. return vec2Value;
  50480. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50481. return vec2Value.add(offsetValue.scale(repeatCount));
  50482. }
  50483. // Size
  50484. case Animation.ANIMATIONTYPE_SIZE:
  50485. switch (loopMode) {
  50486. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50487. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50488. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50489. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50490. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50491. }
  50492. // Color3
  50493. case Animation.ANIMATIONTYPE_COLOR3:
  50494. switch (loopMode) {
  50495. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50496. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50497. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50498. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50499. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50500. }
  50501. // Matrix
  50502. case Animation.ANIMATIONTYPE_MATRIX:
  50503. switch (loopMode) {
  50504. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50505. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50506. if (Animation.AllowMatricesInterpolation) {
  50507. workValue = this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50508. return workValue;
  50509. }
  50510. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50511. return startValue;
  50512. }
  50513. default:
  50514. break;
  50515. }
  50516. break;
  50517. }
  50518. }
  50519. return this._getKeyValue(keys[keys.length - 1].value);
  50520. };
  50521. /**
  50522. * Defines the function to use to interpolate matrices
  50523. * @param startValue defines the start matrix
  50524. * @param endValue defines the end matrix
  50525. * @param gradient defines the gradient between both matrices
  50526. * @param result defines an optional target matrix where to store the interpolation
  50527. * @returns the interpolated matrix
  50528. */
  50529. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50530. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50531. if (result) {
  50532. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50533. return result;
  50534. }
  50535. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50536. }
  50537. if (result) {
  50538. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50539. return result;
  50540. }
  50541. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50542. };
  50543. /**
  50544. * Makes a copy of the animation
  50545. * @returns Cloned animation
  50546. */
  50547. Animation.prototype.clone = function () {
  50548. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50549. clone.enableBlending = this.enableBlending;
  50550. clone.blendingSpeed = this.blendingSpeed;
  50551. if (this._keys) {
  50552. clone.setKeys(this._keys);
  50553. }
  50554. if (this._ranges) {
  50555. clone._ranges = {};
  50556. for (var name in this._ranges) {
  50557. var range = this._ranges[name];
  50558. if (!range) {
  50559. continue;
  50560. }
  50561. clone._ranges[name] = range.clone();
  50562. }
  50563. }
  50564. return clone;
  50565. };
  50566. /**
  50567. * Sets the key frames of the animation
  50568. * @param values The animation key frames to set
  50569. */
  50570. Animation.prototype.setKeys = function (values) {
  50571. this._keys = values.slice(0);
  50572. };
  50573. /**
  50574. * Serializes the animation to an object
  50575. * @returns Serialized object
  50576. */
  50577. Animation.prototype.serialize = function () {
  50578. var serializationObject = {};
  50579. serializationObject.name = this.name;
  50580. serializationObject.property = this.targetProperty;
  50581. serializationObject.framePerSecond = this.framePerSecond;
  50582. serializationObject.dataType = this.dataType;
  50583. serializationObject.loopBehavior = this.loopMode;
  50584. serializationObject.enableBlending = this.enableBlending;
  50585. serializationObject.blendingSpeed = this.blendingSpeed;
  50586. var dataType = this.dataType;
  50587. serializationObject.keys = [];
  50588. var keys = this.getKeys();
  50589. for (var index = 0; index < keys.length; index++) {
  50590. var animationKey = keys[index];
  50591. var key = {};
  50592. key.frame = animationKey.frame;
  50593. switch (dataType) {
  50594. case Animation.ANIMATIONTYPE_FLOAT:
  50595. key.values = [animationKey.value];
  50596. break;
  50597. case Animation.ANIMATIONTYPE_QUATERNION:
  50598. case Animation.ANIMATIONTYPE_MATRIX:
  50599. case Animation.ANIMATIONTYPE_VECTOR3:
  50600. case Animation.ANIMATIONTYPE_COLOR3:
  50601. key.values = animationKey.value.asArray();
  50602. break;
  50603. }
  50604. serializationObject.keys.push(key);
  50605. }
  50606. serializationObject.ranges = [];
  50607. for (var name in this._ranges) {
  50608. var source = this._ranges[name];
  50609. if (!source) {
  50610. continue;
  50611. }
  50612. var range = {};
  50613. range.name = name;
  50614. range.from = source.from;
  50615. range.to = source.to;
  50616. serializationObject.ranges.push(range);
  50617. }
  50618. return serializationObject;
  50619. };
  50620. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50621. /**
  50622. * Get the float animation type
  50623. */
  50624. get: function () {
  50625. return Animation._ANIMATIONTYPE_FLOAT;
  50626. },
  50627. enumerable: true,
  50628. configurable: true
  50629. });
  50630. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50631. /**
  50632. * Get the Vector3 animation type
  50633. */
  50634. get: function () {
  50635. return Animation._ANIMATIONTYPE_VECTOR3;
  50636. },
  50637. enumerable: true,
  50638. configurable: true
  50639. });
  50640. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50641. /**
  50642. * Get the Vectpr2 animation type
  50643. */
  50644. get: function () {
  50645. return Animation._ANIMATIONTYPE_VECTOR2;
  50646. },
  50647. enumerable: true,
  50648. configurable: true
  50649. });
  50650. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50651. /**
  50652. * Get the Size animation type
  50653. */
  50654. get: function () {
  50655. return Animation._ANIMATIONTYPE_SIZE;
  50656. },
  50657. enumerable: true,
  50658. configurable: true
  50659. });
  50660. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50661. /**
  50662. * Get the Quaternion animation type
  50663. */
  50664. get: function () {
  50665. return Animation._ANIMATIONTYPE_QUATERNION;
  50666. },
  50667. enumerable: true,
  50668. configurable: true
  50669. });
  50670. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50671. /**
  50672. * Get the Matrix animation type
  50673. */
  50674. get: function () {
  50675. return Animation._ANIMATIONTYPE_MATRIX;
  50676. },
  50677. enumerable: true,
  50678. configurable: true
  50679. });
  50680. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50681. /**
  50682. * Get the Color3 animation type
  50683. */
  50684. get: function () {
  50685. return Animation._ANIMATIONTYPE_COLOR3;
  50686. },
  50687. enumerable: true,
  50688. configurable: true
  50689. });
  50690. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50691. /**
  50692. * Get the Relative Loop Mode
  50693. */
  50694. get: function () {
  50695. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50696. },
  50697. enumerable: true,
  50698. configurable: true
  50699. });
  50700. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50701. /**
  50702. * Get the Cycle Loop Mode
  50703. */
  50704. get: function () {
  50705. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50706. },
  50707. enumerable: true,
  50708. configurable: true
  50709. });
  50710. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50711. /**
  50712. * Get the Constant Loop Mode
  50713. */
  50714. get: function () {
  50715. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50716. },
  50717. enumerable: true,
  50718. configurable: true
  50719. });
  50720. /**
  50721. * Parses an animation object and creates an animation
  50722. * @param parsedAnimation Parsed animation object
  50723. * @returns Animation object
  50724. */
  50725. Animation.Parse = function (parsedAnimation) {
  50726. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50727. var dataType = parsedAnimation.dataType;
  50728. var keys = [];
  50729. var data;
  50730. var index;
  50731. if (parsedAnimation.enableBlending) {
  50732. animation.enableBlending = parsedAnimation.enableBlending;
  50733. }
  50734. if (parsedAnimation.blendingSpeed) {
  50735. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50736. }
  50737. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50738. var key = parsedAnimation.keys[index];
  50739. var inTangent;
  50740. var outTangent;
  50741. switch (dataType) {
  50742. case Animation.ANIMATIONTYPE_FLOAT:
  50743. data = key.values[0];
  50744. if (key.values.length >= 1) {
  50745. inTangent = key.values[1];
  50746. }
  50747. if (key.values.length >= 2) {
  50748. outTangent = key.values[2];
  50749. }
  50750. break;
  50751. case Animation.ANIMATIONTYPE_QUATERNION:
  50752. data = BABYLON.Quaternion.FromArray(key.values);
  50753. if (key.values.length >= 8) {
  50754. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50755. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50756. inTangent = _inTangent;
  50757. }
  50758. }
  50759. if (key.values.length >= 12) {
  50760. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50761. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50762. outTangent = _outTangent;
  50763. }
  50764. }
  50765. break;
  50766. case Animation.ANIMATIONTYPE_MATRIX:
  50767. data = BABYLON.Matrix.FromArray(key.values);
  50768. break;
  50769. case Animation.ANIMATIONTYPE_COLOR3:
  50770. data = BABYLON.Color3.FromArray(key.values);
  50771. break;
  50772. case Animation.ANIMATIONTYPE_VECTOR3:
  50773. default:
  50774. data = BABYLON.Vector3.FromArray(key.values);
  50775. break;
  50776. }
  50777. var keyData = {};
  50778. keyData.frame = key.frame;
  50779. keyData.value = data;
  50780. if (inTangent != undefined) {
  50781. keyData.inTangent = inTangent;
  50782. }
  50783. if (outTangent != undefined) {
  50784. keyData.outTangent = outTangent;
  50785. }
  50786. keys.push(keyData);
  50787. }
  50788. animation.setKeys(keys);
  50789. if (parsedAnimation.ranges) {
  50790. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50791. data = parsedAnimation.ranges[index];
  50792. animation.createRange(data.name, data.from, data.to);
  50793. }
  50794. }
  50795. return animation;
  50796. };
  50797. /**
  50798. * Appends the serialized animations from the source animations
  50799. * @param source Source containing the animations
  50800. * @param destination Target to store the animations
  50801. */
  50802. Animation.AppendSerializedAnimations = function (source, destination) {
  50803. if (source.animations) {
  50804. destination.animations = [];
  50805. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50806. var animation = source.animations[animationIndex];
  50807. destination.animations.push(animation.serialize());
  50808. }
  50809. }
  50810. };
  50811. /**
  50812. * Use matrix interpolation instead of using direct key value when animating matrices
  50813. */
  50814. Animation.AllowMatricesInterpolation = false;
  50815. /**
  50816. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50817. */
  50818. Animation.AllowMatrixDecomposeForInterpolation = true;
  50819. // Statics
  50820. /**
  50821. * Float animation type
  50822. */
  50823. Animation._ANIMATIONTYPE_FLOAT = 0;
  50824. /**
  50825. * Vector3 animation type
  50826. */
  50827. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50828. /**
  50829. * Quaternion animation type
  50830. */
  50831. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50832. /**
  50833. * Matrix animation type
  50834. */
  50835. Animation._ANIMATIONTYPE_MATRIX = 3;
  50836. /**
  50837. * Color3 animation type
  50838. */
  50839. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50840. /**
  50841. * Vector2 animation type
  50842. */
  50843. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50844. /**
  50845. * Size animation type
  50846. */
  50847. Animation._ANIMATIONTYPE_SIZE = 6;
  50848. /**
  50849. * Relative Loop Mode
  50850. */
  50851. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50852. /**
  50853. * Cycle Loop Mode
  50854. */
  50855. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50856. /**
  50857. * Constant Loop Mode
  50858. */
  50859. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50860. return Animation;
  50861. }());
  50862. BABYLON.Animation = Animation;
  50863. })(BABYLON || (BABYLON = {}));
  50864. //# sourceMappingURL=babylon.animation.js.map
  50865. var BABYLON;
  50866. (function (BABYLON) {
  50867. /**
  50868. * This class defines the direct association between an animation and a target
  50869. */
  50870. var TargetedAnimation = /** @class */ (function () {
  50871. function TargetedAnimation() {
  50872. }
  50873. return TargetedAnimation;
  50874. }());
  50875. BABYLON.TargetedAnimation = TargetedAnimation;
  50876. /**
  50877. * Use this class to create coordinated animations on multiple targets
  50878. */
  50879. var AnimationGroup = /** @class */ (function () {
  50880. function AnimationGroup(name, scene) {
  50881. if (scene === void 0) { scene = null; }
  50882. this.name = name;
  50883. this._targetedAnimations = new Array();
  50884. this._animatables = new Array();
  50885. this._from = Number.MAX_VALUE;
  50886. this._to = -Number.MAX_VALUE;
  50887. this._speedRatio = 1;
  50888. this.onAnimationEndObservable = new BABYLON.Observable();
  50889. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50890. this._scene.animationGroups.push(this);
  50891. }
  50892. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50893. /**
  50894. * Define if the animations are started
  50895. */
  50896. get: function () {
  50897. return this._isStarted;
  50898. },
  50899. enumerable: true,
  50900. configurable: true
  50901. });
  50902. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50903. /**
  50904. * Gets or sets the speed ratio to use for all animations
  50905. */
  50906. get: function () {
  50907. return this._speedRatio;
  50908. },
  50909. /**
  50910. * Gets or sets the speed ratio to use for all animations
  50911. */
  50912. set: function (value) {
  50913. if (this._speedRatio === value) {
  50914. return;
  50915. }
  50916. this._speedRatio = value;
  50917. for (var index = 0; index < this._animatables.length; index++) {
  50918. var animatable = this._animatables[index];
  50919. animatable.speedRatio = this._speedRatio;
  50920. }
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50926. /**
  50927. * Gets the targeted animations for this animation group
  50928. */
  50929. get: function () {
  50930. return this._targetedAnimations;
  50931. },
  50932. enumerable: true,
  50933. configurable: true
  50934. });
  50935. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50936. /**
  50937. * returning the list of animatables controlled by this animation group.
  50938. */
  50939. get: function () {
  50940. return this._animatables;
  50941. },
  50942. enumerable: true,
  50943. configurable: true
  50944. });
  50945. /**
  50946. * Add an animation (with its target) in the group
  50947. * @param animation defines the animation we want to add
  50948. * @param target defines the target of the animation
  50949. * @returns the {BABYLON.TargetedAnimation} object
  50950. */
  50951. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50952. var targetedAnimation = {
  50953. animation: animation,
  50954. target: target
  50955. };
  50956. var keys = animation.getKeys();
  50957. if (this._from > keys[0].frame) {
  50958. this._from = keys[0].frame;
  50959. }
  50960. if (this._to < keys[keys.length - 1].frame) {
  50961. this._to = keys[keys.length - 1].frame;
  50962. }
  50963. this._targetedAnimations.push(targetedAnimation);
  50964. return targetedAnimation;
  50965. };
  50966. /**
  50967. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50968. * It can add constant keys at begin or end
  50969. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  50970. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  50971. */
  50972. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50973. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  50974. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  50975. beginFrame = Math.max(beginFrame, this._from);
  50976. endFrame = Math.min(endFrame, this._to);
  50977. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50978. var targetedAnimation = this._targetedAnimations[index];
  50979. var keys = targetedAnimation.animation.getKeys();
  50980. var startKey = keys[0];
  50981. var endKey = keys[keys.length - 1];
  50982. if (startKey.frame > beginFrame) {
  50983. var newKey = {
  50984. frame: beginFrame,
  50985. value: startKey.value,
  50986. inTangent: startKey.inTangent,
  50987. outTangent: startKey.outTangent,
  50988. interpolation: startKey.interpolation
  50989. };
  50990. keys.splice(0, 0, newKey);
  50991. }
  50992. if (endKey.frame < endFrame) {
  50993. var newKey = {
  50994. frame: endFrame,
  50995. value: endKey.value,
  50996. inTangent: endKey.outTangent,
  50997. outTangent: endKey.outTangent,
  50998. interpolation: endKey.interpolation
  50999. };
  51000. keys.push(newKey);
  51001. }
  51002. }
  51003. return this;
  51004. };
  51005. /**
  51006. * Start all animations on given targets
  51007. * @param loop defines if animations must loop
  51008. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51009. * @param from defines the from key (optional)
  51010. * @param to defines the to key (optional)
  51011. * @returns the current animation group
  51012. */
  51013. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51014. var _this = this;
  51015. if (loop === void 0) { loop = false; }
  51016. if (speedRatio === void 0) { speedRatio = 1; }
  51017. if (this._isStarted || this._targetedAnimations.length === 0) {
  51018. return this;
  51019. }
  51020. var _loop_1 = function (targetedAnimation) {
  51021. 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 () {
  51022. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51023. }));
  51024. };
  51025. var this_1 = this;
  51026. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51027. var targetedAnimation = _a[_i];
  51028. _loop_1(targetedAnimation);
  51029. }
  51030. this._speedRatio = speedRatio;
  51031. this._isStarted = true;
  51032. return this;
  51033. };
  51034. /**
  51035. * Pause all animations
  51036. */
  51037. AnimationGroup.prototype.pause = function () {
  51038. if (!this._isStarted) {
  51039. return this;
  51040. }
  51041. for (var index = 0; index < this._animatables.length; index++) {
  51042. var animatable = this._animatables[index];
  51043. animatable.pause();
  51044. }
  51045. return this;
  51046. };
  51047. /**
  51048. * Play all animations to initial state
  51049. * This function will start() the animations if they were not started or will restart() them if they were paused
  51050. * @param loop defines if animations must loop
  51051. */
  51052. AnimationGroup.prototype.play = function (loop) {
  51053. if (this.isStarted) {
  51054. if (loop !== undefined) {
  51055. for (var index = 0; index < this._animatables.length; index++) {
  51056. var animatable = this._animatables[index];
  51057. animatable.loopAnimation = loop;
  51058. }
  51059. }
  51060. this.restart();
  51061. }
  51062. else {
  51063. this.start(loop, this._speedRatio);
  51064. }
  51065. return this;
  51066. };
  51067. /**
  51068. * Reset all animations to initial state
  51069. */
  51070. AnimationGroup.prototype.reset = function () {
  51071. if (!this._isStarted) {
  51072. return this;
  51073. }
  51074. for (var index = 0; index < this._animatables.length; index++) {
  51075. var animatable = this._animatables[index];
  51076. animatable.reset();
  51077. }
  51078. return this;
  51079. };
  51080. /**
  51081. * Restart animations from key 0
  51082. */
  51083. AnimationGroup.prototype.restart = function () {
  51084. if (!this._isStarted) {
  51085. return this;
  51086. }
  51087. for (var index = 0; index < this._animatables.length; index++) {
  51088. var animatable = this._animatables[index];
  51089. animatable.restart();
  51090. }
  51091. return this;
  51092. };
  51093. /**
  51094. * Stop all animations
  51095. */
  51096. AnimationGroup.prototype.stop = function () {
  51097. if (!this._isStarted) {
  51098. return this;
  51099. }
  51100. for (var index = 0; index < this._animatables.length; index++) {
  51101. var animatable = this._animatables[index];
  51102. animatable.stop();
  51103. }
  51104. this._isStarted = false;
  51105. return this;
  51106. };
  51107. /**
  51108. * Set animation weight for all animatables
  51109. * @param weight defines the weight to use
  51110. * @return the animationGroup
  51111. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51112. */
  51113. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51114. for (var index = 0; index < this._animatables.length; index++) {
  51115. var animatable = this._animatables[index];
  51116. animatable.weight = weight;
  51117. }
  51118. return this;
  51119. };
  51120. /**
  51121. * Synchronize and normalize all animatables with a source animatable
  51122. * @param root defines the root animatable to synchronize with
  51123. * @return the animationGroup
  51124. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51125. */
  51126. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51127. for (var index = 0; index < this._animatables.length; index++) {
  51128. var animatable = this._animatables[index];
  51129. animatable.syncWith(root);
  51130. }
  51131. return this;
  51132. };
  51133. /**
  51134. * Goes to a specific frame in this animation group
  51135. * @param frame the frame number to go to
  51136. * @return the animationGroup
  51137. */
  51138. AnimationGroup.prototype.goToFrame = function (frame) {
  51139. if (!this._isStarted) {
  51140. return this;
  51141. }
  51142. for (var index = 0; index < this._animatables.length; index++) {
  51143. var animatable = this._animatables[index];
  51144. animatable.goToFrame(frame);
  51145. }
  51146. return this;
  51147. };
  51148. /**
  51149. * Dispose all associated resources
  51150. */
  51151. AnimationGroup.prototype.dispose = function () {
  51152. this._targetedAnimations = [];
  51153. this._animatables = [];
  51154. var index = this._scene.animationGroups.indexOf(this);
  51155. if (index > -1) {
  51156. this._scene.animationGroups.splice(index, 1);
  51157. }
  51158. };
  51159. return AnimationGroup;
  51160. }());
  51161. BABYLON.AnimationGroup = AnimationGroup;
  51162. })(BABYLON || (BABYLON = {}));
  51163. //# sourceMappingURL=babylon.animationGroup.js.map
  51164. var BABYLON;
  51165. (function (BABYLON) {
  51166. /**
  51167. * Defines a runtime animation
  51168. */
  51169. var RuntimeAnimation = /** @class */ (function () {
  51170. /**
  51171. * Create a new RuntimeAnimation object
  51172. * @param target defines the target of the animation
  51173. * @param animation defines the source animation object
  51174. * @param scene defines the hosting scene
  51175. * @param host defines the initiating Animatable
  51176. */
  51177. function RuntimeAnimation(target, animation, scene, host) {
  51178. /**
  51179. * The current frame of the runtime animation
  51180. */
  51181. this._currentFrame = 0;
  51182. /**
  51183. * The offsets cache of the runtime animation
  51184. */
  51185. this._offsetsCache = {};
  51186. /**
  51187. * The high limits cache of the runtime animation
  51188. */
  51189. this._highLimitsCache = {};
  51190. /**
  51191. * Specifies if the runtime animation has been stopped
  51192. */
  51193. this._stopped = false;
  51194. /**
  51195. * The blending factor of the runtime animation
  51196. */
  51197. this._blendingFactor = 0;
  51198. /**
  51199. * The target path of the runtime animation
  51200. */
  51201. this._targetPath = "";
  51202. /**
  51203. * The weight of the runtime animation
  51204. */
  51205. this._weight = 1.0;
  51206. /**
  51207. * The ratio offset of the runtime animation
  51208. */
  51209. this._ratioOffset = 0;
  51210. /**
  51211. * The previous delay of the runtime animation
  51212. */
  51213. this._previousDelay = 0;
  51214. /**
  51215. * The previous ratio of the runtime animation
  51216. */
  51217. this._previousRatio = 0;
  51218. this._animation = animation;
  51219. this._target = target;
  51220. this._scene = scene;
  51221. this._host = host;
  51222. animation._runtimeAnimations.push(this);
  51223. }
  51224. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51225. /**
  51226. * Gets the current frame of the runtime animation
  51227. */
  51228. get: function () {
  51229. return this._currentFrame;
  51230. },
  51231. enumerable: true,
  51232. configurable: true
  51233. });
  51234. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51235. /**
  51236. * Gets the weight of the runtime animation
  51237. */
  51238. get: function () {
  51239. return this._weight;
  51240. },
  51241. enumerable: true,
  51242. configurable: true
  51243. });
  51244. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51245. /**
  51246. * Gets the original value of the runtime animation
  51247. */
  51248. get: function () {
  51249. return this._originalValue;
  51250. },
  51251. enumerable: true,
  51252. configurable: true
  51253. });
  51254. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51255. /**
  51256. * Gets the current value of the runtime animation
  51257. */
  51258. get: function () {
  51259. return this._currentValue;
  51260. },
  51261. enumerable: true,
  51262. configurable: true
  51263. });
  51264. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51265. /**
  51266. * Gets the target path of the runtime animation
  51267. */
  51268. get: function () {
  51269. return this._targetPath;
  51270. },
  51271. enumerable: true,
  51272. configurable: true
  51273. });
  51274. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51275. /**
  51276. * Gets the actual target of the runtime animation
  51277. */
  51278. get: function () {
  51279. return this._activeTarget;
  51280. },
  51281. enumerable: true,
  51282. configurable: true
  51283. });
  51284. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51285. /**
  51286. * Gets the animation from the runtime animation
  51287. */
  51288. get: function () {
  51289. return this._animation;
  51290. },
  51291. enumerable: true,
  51292. configurable: true
  51293. });
  51294. /**
  51295. * Resets the runtime animation to the beginning
  51296. */
  51297. RuntimeAnimation.prototype.reset = function () {
  51298. this._offsetsCache = {};
  51299. this._highLimitsCache = {};
  51300. this._currentFrame = 0;
  51301. this._blendingFactor = 0;
  51302. this._originalValue = null;
  51303. };
  51304. /**
  51305. * Specifies if the runtime animation is stopped
  51306. * @returns Boolean specifying if the runtime animation is stopped
  51307. */
  51308. RuntimeAnimation.prototype.isStopped = function () {
  51309. return this._stopped;
  51310. };
  51311. /**
  51312. * Disposes of the runtime animation
  51313. */
  51314. RuntimeAnimation.prototype.dispose = function () {
  51315. var index = this._animation.runtimeAnimations.indexOf(this);
  51316. if (index > -1) {
  51317. this._animation.runtimeAnimations.splice(index, 1);
  51318. }
  51319. };
  51320. /**
  51321. * Interpolates the animation from the current frame
  51322. * @param currentFrame The frame to interpolate the animation to
  51323. * @param repeatCount The number of times that the animation should loop
  51324. * @param loopMode The type of looping mode to use
  51325. * @param offsetValue Animation offset value
  51326. * @param highLimitValue The high limit value
  51327. * @returns The interpolated value
  51328. */
  51329. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51330. this._currentFrame = currentFrame;
  51331. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51332. };
  51333. /**
  51334. * Affect the interpolated value to the target
  51335. * @param currentValue defines the value computed by the animation
  51336. * @param weight defines the weight to apply to this value
  51337. */
  51338. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51339. if (weight === void 0) { weight = 1.0; }
  51340. if (this._target instanceof Array) {
  51341. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51342. var target = _a[_i];
  51343. this._setValue(target, currentValue, weight);
  51344. }
  51345. }
  51346. else {
  51347. this._setValue(this._target, currentValue, weight);
  51348. }
  51349. };
  51350. /**
  51351. * Sets the value of the runtime animation
  51352. * @param target The target property of the runtime animation
  51353. * @param currentValue The current value to use for the runtime animation
  51354. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51355. */
  51356. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51357. if (weight === void 0) { weight = 1.0; }
  51358. // Set value
  51359. var path;
  51360. var destination;
  51361. var targetPropertyPath = this._animation.targetPropertyPath;
  51362. if (targetPropertyPath.length > 1) {
  51363. var property = target[targetPropertyPath[0]];
  51364. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51365. property = property[targetPropertyPath[index]];
  51366. }
  51367. path = targetPropertyPath[targetPropertyPath.length - 1];
  51368. destination = property;
  51369. }
  51370. else {
  51371. path = targetPropertyPath[0];
  51372. destination = target;
  51373. }
  51374. this._targetPath = path;
  51375. this._activeTarget = destination;
  51376. this._weight = weight;
  51377. // Blending
  51378. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51379. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51380. if (enableBlending && this._blendingFactor <= 1.0) {
  51381. if (!this._originalBlendValue) {
  51382. var originalValue = destination[path];
  51383. if (originalValue.clone) {
  51384. this._originalBlendValue = originalValue.clone();
  51385. }
  51386. else {
  51387. this._originalBlendValue = originalValue;
  51388. }
  51389. }
  51390. }
  51391. if (weight !== -1.0) {
  51392. if (!this._originalValue) {
  51393. var originalValue = void 0;
  51394. if (destination.getRestPose) { // For bones
  51395. originalValue = destination.getRestPose();
  51396. }
  51397. else {
  51398. originalValue = destination[path];
  51399. }
  51400. if (originalValue.clone) {
  51401. this._originalValue = originalValue.clone();
  51402. }
  51403. else {
  51404. this._originalValue = originalValue;
  51405. }
  51406. }
  51407. }
  51408. if (enableBlending && this._blendingFactor <= 1.0) {
  51409. if (this._originalBlendValue.m) { // Matrix
  51410. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51411. if (this._currentValue) {
  51412. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51413. }
  51414. else {
  51415. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51416. }
  51417. }
  51418. else {
  51419. if (this._currentValue) {
  51420. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51421. }
  51422. else {
  51423. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51424. }
  51425. }
  51426. }
  51427. else {
  51428. var constructor = this._originalBlendValue.constructor;
  51429. if (constructor.Lerp) { // Lerp supported
  51430. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51431. }
  51432. else if (constructor.Slerp) { // Slerp supported
  51433. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51434. }
  51435. else if (this._originalBlendValue.toFixed) { // Number
  51436. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51437. }
  51438. else { // Blending not supported
  51439. this._currentValue = currentValue;
  51440. }
  51441. }
  51442. this._blendingFactor += blendingSpeed;
  51443. }
  51444. else {
  51445. this._currentValue = currentValue;
  51446. }
  51447. if (weight !== -1.0) {
  51448. this._scene._registerTargetForLateAnimationBinding(this);
  51449. }
  51450. else {
  51451. destination[path] = this._currentValue;
  51452. }
  51453. if (target.markAsDirty) {
  51454. target.markAsDirty(this._animation.targetProperty);
  51455. }
  51456. };
  51457. /**
  51458. * Gets the loop pmode of the runtime animation
  51459. * @returns Loop Mode
  51460. */
  51461. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51462. if (this._target && this._target.animationPropertiesOverride) {
  51463. return this._target.animationPropertiesOverride.loopMode;
  51464. }
  51465. return this._animation.loopMode;
  51466. };
  51467. /**
  51468. * Move the current animation to a given frame
  51469. * @param frame defines the frame to move to
  51470. */
  51471. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51472. var keys = this._animation.getKeys();
  51473. if (frame < keys[0].frame) {
  51474. frame = keys[0].frame;
  51475. }
  51476. else if (frame > keys[keys.length - 1].frame) {
  51477. frame = keys[keys.length - 1].frame;
  51478. }
  51479. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51480. this.setValue(currentValue, -1);
  51481. };
  51482. /**
  51483. * @ignore Internal use only
  51484. */
  51485. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51486. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51487. this._ratioOffset = this._previousRatio - newRatio;
  51488. };
  51489. /**
  51490. * Execute the current animation
  51491. * @param delay defines the delay to add to the current frame
  51492. * @param from defines the lower bound of the animation range
  51493. * @param to defines the upper bound of the animation range
  51494. * @param loop defines if the current animation must loop
  51495. * @param speedRatio defines the current speed ratio
  51496. * @param weight defines the weight of the animation (default is -1 so no weight)
  51497. * @returns a boolean indicating if the animation has ended
  51498. */
  51499. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51500. if (weight === void 0) { weight = -1.0; }
  51501. var targetPropertyPath = this._animation.targetPropertyPath;
  51502. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51503. this._stopped = true;
  51504. return false;
  51505. }
  51506. var returnValue = true;
  51507. var keys = this._animation.getKeys();
  51508. // Adding a start key at frame 0 if missing
  51509. if (keys[0].frame !== 0) {
  51510. var newKey = { frame: 0, value: keys[0].value };
  51511. keys.splice(0, 0, newKey);
  51512. }
  51513. // Check limits
  51514. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51515. from = keys[0].frame;
  51516. }
  51517. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51518. to = keys[keys.length - 1].frame;
  51519. }
  51520. //to and from cannot be the same key
  51521. if (from === to) {
  51522. if (from > keys[0].frame) {
  51523. from--;
  51524. }
  51525. else if (to < keys[keys.length - 1].frame) {
  51526. to++;
  51527. }
  51528. }
  51529. // Compute ratio
  51530. var range = to - from;
  51531. var offsetValue;
  51532. // ratio represents the frame delta between from and to
  51533. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51534. var highLimitValue = 0;
  51535. this._previousDelay = delay;
  51536. this._previousRatio = ratio;
  51537. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51538. returnValue = false;
  51539. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51540. }
  51541. else {
  51542. // Get max value if required
  51543. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51544. var keyOffset = to.toString() + from.toString();
  51545. if (!this._offsetsCache[keyOffset]) {
  51546. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51547. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51548. switch (this._animation.dataType) {
  51549. // Float
  51550. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51551. this._offsetsCache[keyOffset] = toValue - fromValue;
  51552. break;
  51553. // Quaternion
  51554. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51555. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51556. break;
  51557. // Vector3
  51558. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51559. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51560. // Vector2
  51561. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51562. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51563. // Size
  51564. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51565. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51566. // Color3
  51567. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51568. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51569. default:
  51570. break;
  51571. }
  51572. this._highLimitsCache[keyOffset] = toValue;
  51573. }
  51574. highLimitValue = this._highLimitsCache[keyOffset];
  51575. offsetValue = this._offsetsCache[keyOffset];
  51576. }
  51577. }
  51578. if (offsetValue === undefined) {
  51579. switch (this._animation.dataType) {
  51580. // Float
  51581. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51582. offsetValue = 0;
  51583. break;
  51584. // Quaternion
  51585. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51586. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51587. break;
  51588. // Vector3
  51589. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51590. offsetValue = BABYLON.Vector3.Zero();
  51591. break;
  51592. // Vector2
  51593. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51594. offsetValue = BABYLON.Vector2.Zero();
  51595. break;
  51596. // Size
  51597. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51598. offsetValue = BABYLON.Size.Zero();
  51599. break;
  51600. // Color3
  51601. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51602. offsetValue = BABYLON.Color3.Black();
  51603. }
  51604. }
  51605. // Compute value
  51606. var repeatCount = (ratio / range) >> 0;
  51607. var currentFrame = returnValue ? from + ratio % range : to;
  51608. // Need to normalize?
  51609. if (this._host && this._host.syncRoot) {
  51610. var syncRoot = this._host.syncRoot;
  51611. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51612. currentFrame = from + (to - from) * hostNormalizedFrame;
  51613. }
  51614. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51615. // Set value
  51616. this.setValue(currentValue, weight);
  51617. // Check events
  51618. var events = this._animation.getEvents();
  51619. for (var index = 0; index < events.length; index++) {
  51620. // Make sure current frame has passed event frame and that event frame is within the current range
  51621. // Also, handle both forward and reverse animations
  51622. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51623. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51624. var event = events[index];
  51625. if (!event.isDone) {
  51626. // If event should be done only once, remove it.
  51627. if (event.onlyOnce) {
  51628. events.splice(index, 1);
  51629. index--;
  51630. }
  51631. event.isDone = true;
  51632. event.action();
  51633. } // Don't do anything if the event has already be done.
  51634. }
  51635. else if (events[index].isDone && !events[index].onlyOnce) {
  51636. // reset event, the animation is looping
  51637. events[index].isDone = false;
  51638. }
  51639. }
  51640. if (!returnValue) {
  51641. this._stopped = true;
  51642. }
  51643. return returnValue;
  51644. };
  51645. return RuntimeAnimation;
  51646. }());
  51647. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51648. })(BABYLON || (BABYLON = {}));
  51649. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51650. var BABYLON;
  51651. (function (BABYLON) {
  51652. var Animatable = /** @class */ (function () {
  51653. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51654. if (fromFrame === void 0) { fromFrame = 0; }
  51655. if (toFrame === void 0) { toFrame = 100; }
  51656. if (loopAnimation === void 0) { loopAnimation = false; }
  51657. if (speedRatio === void 0) { speedRatio = 1.0; }
  51658. this.target = target;
  51659. this.fromFrame = fromFrame;
  51660. this.toFrame = toFrame;
  51661. this.loopAnimation = loopAnimation;
  51662. this.onAnimationEnd = onAnimationEnd;
  51663. this._localDelayOffset = null;
  51664. this._pausedDelay = null;
  51665. this._runtimeAnimations = new Array();
  51666. this._paused = false;
  51667. this._speedRatio = 1;
  51668. this._weight = -1.0;
  51669. this.animationStarted = false;
  51670. this._scene = scene;
  51671. if (animations) {
  51672. this.appendAnimations(target, animations);
  51673. }
  51674. this._speedRatio = speedRatio;
  51675. scene._activeAnimatables.push(this);
  51676. }
  51677. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51678. /**
  51679. * Gets the root Animatable used to synchronize and normalize animations
  51680. */
  51681. get: function () {
  51682. return this._syncRoot;
  51683. },
  51684. enumerable: true,
  51685. configurable: true
  51686. });
  51687. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51688. /**
  51689. * Gets the current frame of the first RuntimeAnimation
  51690. * Used to synchronize Animatables
  51691. */
  51692. get: function () {
  51693. if (this._runtimeAnimations.length === 0) {
  51694. return 0;
  51695. }
  51696. return this._runtimeAnimations[0].currentFrame;
  51697. },
  51698. enumerable: true,
  51699. configurable: true
  51700. });
  51701. Object.defineProperty(Animatable.prototype, "weight", {
  51702. /**
  51703. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51704. */
  51705. get: function () {
  51706. return this._weight;
  51707. },
  51708. set: function (value) {
  51709. if (value === -1) { // -1 is ok and means no weight
  51710. this._weight = -1;
  51711. return;
  51712. }
  51713. // Else weight must be in [0, 1] range
  51714. this._weight = Math.min(Math.max(value, 0), 1.0);
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51720. /**
  51721. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51722. */
  51723. get: function () {
  51724. return this._speedRatio;
  51725. },
  51726. set: function (value) {
  51727. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51728. var animation = this._runtimeAnimations[index];
  51729. animation._prepareForSpeedRatioChange(value);
  51730. }
  51731. this._speedRatio = value;
  51732. },
  51733. enumerable: true,
  51734. configurable: true
  51735. });
  51736. // Methods
  51737. /**
  51738. * Synchronize and normalize current Animatable with a source Animatable
  51739. * This is useful when using animation weights and when animations are not of the same length
  51740. * @param root defines the root Animatable to synchronize with
  51741. * @returns the current Animatable
  51742. */
  51743. Animatable.prototype.syncWith = function (root) {
  51744. this._syncRoot = root;
  51745. if (root) {
  51746. // Make sure this animatable will animate after the root
  51747. var index = this._scene._activeAnimatables.indexOf(this);
  51748. if (index > -1) {
  51749. this._scene._activeAnimatables.splice(index, 1);
  51750. this._scene._activeAnimatables.push(this);
  51751. }
  51752. }
  51753. return this;
  51754. };
  51755. Animatable.prototype.getAnimations = function () {
  51756. return this._runtimeAnimations;
  51757. };
  51758. Animatable.prototype.appendAnimations = function (target, animations) {
  51759. for (var index = 0; index < animations.length; index++) {
  51760. var animation = animations[index];
  51761. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51762. }
  51763. };
  51764. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51765. var runtimeAnimations = this._runtimeAnimations;
  51766. for (var index = 0; index < runtimeAnimations.length; index++) {
  51767. if (runtimeAnimations[index].animation.targetProperty === property) {
  51768. return runtimeAnimations[index].animation;
  51769. }
  51770. }
  51771. return null;
  51772. };
  51773. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51774. var runtimeAnimations = this._runtimeAnimations;
  51775. for (var index = 0; index < runtimeAnimations.length; index++) {
  51776. if (runtimeAnimations[index].animation.targetProperty === property) {
  51777. return runtimeAnimations[index];
  51778. }
  51779. }
  51780. return null;
  51781. };
  51782. Animatable.prototype.reset = function () {
  51783. var runtimeAnimations = this._runtimeAnimations;
  51784. for (var index = 0; index < runtimeAnimations.length; index++) {
  51785. runtimeAnimations[index].reset();
  51786. }
  51787. // Reset to original value
  51788. for (index = 0; index < runtimeAnimations.length; index++) {
  51789. var animation = runtimeAnimations[index];
  51790. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51791. }
  51792. this._localDelayOffset = null;
  51793. this._pausedDelay = null;
  51794. };
  51795. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51796. var runtimeAnimations = this._runtimeAnimations;
  51797. for (var index = 0; index < runtimeAnimations.length; index++) {
  51798. runtimeAnimations[index].animation.enableBlending = true;
  51799. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51800. }
  51801. };
  51802. Animatable.prototype.disableBlending = function () {
  51803. var runtimeAnimations = this._runtimeAnimations;
  51804. for (var index = 0; index < runtimeAnimations.length; index++) {
  51805. runtimeAnimations[index].animation.enableBlending = false;
  51806. }
  51807. };
  51808. Animatable.prototype.goToFrame = function (frame) {
  51809. var runtimeAnimations = this._runtimeAnimations;
  51810. if (runtimeAnimations[0]) {
  51811. var fps = runtimeAnimations[0].animation.framePerSecond;
  51812. var currentFrame = runtimeAnimations[0].currentFrame;
  51813. var adjustTime = frame - currentFrame;
  51814. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51815. if (this._localDelayOffset === null) {
  51816. this._localDelayOffset = 0;
  51817. }
  51818. this._localDelayOffset -= delay;
  51819. }
  51820. for (var index = 0; index < runtimeAnimations.length; index++) {
  51821. runtimeAnimations[index].goToFrame(frame);
  51822. }
  51823. };
  51824. Animatable.prototype.pause = function () {
  51825. if (this._paused) {
  51826. return;
  51827. }
  51828. this._paused = true;
  51829. };
  51830. Animatable.prototype.restart = function () {
  51831. this._paused = false;
  51832. };
  51833. Animatable.prototype.stop = function (animationName) {
  51834. if (animationName) {
  51835. var idx = this._scene._activeAnimatables.indexOf(this);
  51836. if (idx > -1) {
  51837. var runtimeAnimations = this._runtimeAnimations;
  51838. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51839. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51840. continue;
  51841. }
  51842. runtimeAnimations[index].dispose();
  51843. runtimeAnimations.splice(index, 1);
  51844. }
  51845. if (runtimeAnimations.length == 0) {
  51846. this._scene._activeAnimatables.splice(idx, 1);
  51847. if (this.onAnimationEnd) {
  51848. this.onAnimationEnd();
  51849. }
  51850. }
  51851. }
  51852. }
  51853. else {
  51854. var index = this._scene._activeAnimatables.indexOf(this);
  51855. if (index > -1) {
  51856. this._scene._activeAnimatables.splice(index, 1);
  51857. var runtimeAnimations = this._runtimeAnimations;
  51858. for (var index = 0; index < runtimeAnimations.length; index++) {
  51859. runtimeAnimations[index].dispose();
  51860. }
  51861. if (this.onAnimationEnd) {
  51862. this.onAnimationEnd();
  51863. }
  51864. }
  51865. }
  51866. };
  51867. Animatable.prototype._animate = function (delay) {
  51868. if (this._paused) {
  51869. this.animationStarted = false;
  51870. if (this._pausedDelay === null) {
  51871. this._pausedDelay = delay;
  51872. }
  51873. return true;
  51874. }
  51875. if (this._localDelayOffset === null) {
  51876. this._localDelayOffset = delay;
  51877. this._pausedDelay = null;
  51878. }
  51879. else if (this._pausedDelay !== null) {
  51880. this._localDelayOffset += delay - this._pausedDelay;
  51881. this._pausedDelay = null;
  51882. }
  51883. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51884. return true;
  51885. }
  51886. // Animating
  51887. var running = false;
  51888. var runtimeAnimations = this._runtimeAnimations;
  51889. var index;
  51890. for (index = 0; index < runtimeAnimations.length; index++) {
  51891. var animation = runtimeAnimations[index];
  51892. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51893. running = running || isRunning;
  51894. }
  51895. this.animationStarted = running;
  51896. if (!running) {
  51897. // Remove from active animatables
  51898. index = this._scene._activeAnimatables.indexOf(this);
  51899. this._scene._activeAnimatables.splice(index, 1);
  51900. // Dispose all runtime animations
  51901. for (index = 0; index < runtimeAnimations.length; index++) {
  51902. runtimeAnimations[index].dispose();
  51903. }
  51904. }
  51905. if (!running && this.onAnimationEnd) {
  51906. this.onAnimationEnd();
  51907. this.onAnimationEnd = null;
  51908. }
  51909. return running;
  51910. };
  51911. return Animatable;
  51912. }());
  51913. BABYLON.Animatable = Animatable;
  51914. })(BABYLON || (BABYLON = {}));
  51915. //# sourceMappingURL=babylon.animatable.js.map
  51916. var BABYLON;
  51917. (function (BABYLON) {
  51918. var EasingFunction = /** @class */ (function () {
  51919. function EasingFunction() {
  51920. // Properties
  51921. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51922. }
  51923. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51924. get: function () {
  51925. return EasingFunction._EASINGMODE_EASEIN;
  51926. },
  51927. enumerable: true,
  51928. configurable: true
  51929. });
  51930. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51931. get: function () {
  51932. return EasingFunction._EASINGMODE_EASEOUT;
  51933. },
  51934. enumerable: true,
  51935. configurable: true
  51936. });
  51937. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51938. get: function () {
  51939. return EasingFunction._EASINGMODE_EASEINOUT;
  51940. },
  51941. enumerable: true,
  51942. configurable: true
  51943. });
  51944. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51945. var n = Math.min(Math.max(easingMode, 0), 2);
  51946. this._easingMode = n;
  51947. };
  51948. EasingFunction.prototype.getEasingMode = function () {
  51949. return this._easingMode;
  51950. };
  51951. EasingFunction.prototype.easeInCore = function (gradient) {
  51952. throw new Error('You must implement this method');
  51953. };
  51954. EasingFunction.prototype.ease = function (gradient) {
  51955. switch (this._easingMode) {
  51956. case EasingFunction.EASINGMODE_EASEIN:
  51957. return this.easeInCore(gradient);
  51958. case EasingFunction.EASINGMODE_EASEOUT:
  51959. return (1 - this.easeInCore(1 - gradient));
  51960. }
  51961. if (gradient >= 0.5) {
  51962. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51963. }
  51964. return (this.easeInCore(gradient * 2) * 0.5);
  51965. };
  51966. //Statics
  51967. EasingFunction._EASINGMODE_EASEIN = 0;
  51968. EasingFunction._EASINGMODE_EASEOUT = 1;
  51969. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51970. return EasingFunction;
  51971. }());
  51972. BABYLON.EasingFunction = EasingFunction;
  51973. var CircleEase = /** @class */ (function (_super) {
  51974. __extends(CircleEase, _super);
  51975. function CircleEase() {
  51976. return _super !== null && _super.apply(this, arguments) || this;
  51977. }
  51978. CircleEase.prototype.easeInCore = function (gradient) {
  51979. gradient = Math.max(0, Math.min(1, gradient));
  51980. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51981. };
  51982. return CircleEase;
  51983. }(EasingFunction));
  51984. BABYLON.CircleEase = CircleEase;
  51985. var BackEase = /** @class */ (function (_super) {
  51986. __extends(BackEase, _super);
  51987. function BackEase(amplitude) {
  51988. if (amplitude === void 0) { amplitude = 1; }
  51989. var _this = _super.call(this) || this;
  51990. _this.amplitude = amplitude;
  51991. return _this;
  51992. }
  51993. BackEase.prototype.easeInCore = function (gradient) {
  51994. var num = Math.max(0, this.amplitude);
  51995. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51996. };
  51997. return BackEase;
  51998. }(EasingFunction));
  51999. BABYLON.BackEase = BackEase;
  52000. var BounceEase = /** @class */ (function (_super) {
  52001. __extends(BounceEase, _super);
  52002. function BounceEase(bounces, bounciness) {
  52003. if (bounces === void 0) { bounces = 3; }
  52004. if (bounciness === void 0) { bounciness = 2; }
  52005. var _this = _super.call(this) || this;
  52006. _this.bounces = bounces;
  52007. _this.bounciness = bounciness;
  52008. return _this;
  52009. }
  52010. BounceEase.prototype.easeInCore = function (gradient) {
  52011. var y = Math.max(0.0, this.bounces);
  52012. var bounciness = this.bounciness;
  52013. if (bounciness <= 1.0) {
  52014. bounciness = 1.001;
  52015. }
  52016. var num9 = Math.pow(bounciness, y);
  52017. var num5 = 1.0 - bounciness;
  52018. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52019. var num15 = gradient * num4;
  52020. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52021. var num3 = Math.floor(num65);
  52022. var num13 = num3 + 1.0;
  52023. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52024. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52025. var num7 = (num8 + num12) * 0.5;
  52026. var num6 = gradient - num7;
  52027. var num2 = num7 - num8;
  52028. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52029. };
  52030. return BounceEase;
  52031. }(EasingFunction));
  52032. BABYLON.BounceEase = BounceEase;
  52033. var CubicEase = /** @class */ (function (_super) {
  52034. __extends(CubicEase, _super);
  52035. function CubicEase() {
  52036. return _super !== null && _super.apply(this, arguments) || this;
  52037. }
  52038. CubicEase.prototype.easeInCore = function (gradient) {
  52039. return (gradient * gradient * gradient);
  52040. };
  52041. return CubicEase;
  52042. }(EasingFunction));
  52043. BABYLON.CubicEase = CubicEase;
  52044. var ElasticEase = /** @class */ (function (_super) {
  52045. __extends(ElasticEase, _super);
  52046. function ElasticEase(oscillations, springiness) {
  52047. if (oscillations === void 0) { oscillations = 3; }
  52048. if (springiness === void 0) { springiness = 3; }
  52049. var _this = _super.call(this) || this;
  52050. _this.oscillations = oscillations;
  52051. _this.springiness = springiness;
  52052. return _this;
  52053. }
  52054. ElasticEase.prototype.easeInCore = function (gradient) {
  52055. var num2;
  52056. var num3 = Math.max(0.0, this.oscillations);
  52057. var num = Math.max(0.0, this.springiness);
  52058. if (num == 0) {
  52059. num2 = gradient;
  52060. }
  52061. else {
  52062. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52063. }
  52064. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52065. };
  52066. return ElasticEase;
  52067. }(EasingFunction));
  52068. BABYLON.ElasticEase = ElasticEase;
  52069. var ExponentialEase = /** @class */ (function (_super) {
  52070. __extends(ExponentialEase, _super);
  52071. function ExponentialEase(exponent) {
  52072. if (exponent === void 0) { exponent = 2; }
  52073. var _this = _super.call(this) || this;
  52074. _this.exponent = exponent;
  52075. return _this;
  52076. }
  52077. ExponentialEase.prototype.easeInCore = function (gradient) {
  52078. if (this.exponent <= 0) {
  52079. return gradient;
  52080. }
  52081. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52082. };
  52083. return ExponentialEase;
  52084. }(EasingFunction));
  52085. BABYLON.ExponentialEase = ExponentialEase;
  52086. var PowerEase = /** @class */ (function (_super) {
  52087. __extends(PowerEase, _super);
  52088. function PowerEase(power) {
  52089. if (power === void 0) { power = 2; }
  52090. var _this = _super.call(this) || this;
  52091. _this.power = power;
  52092. return _this;
  52093. }
  52094. PowerEase.prototype.easeInCore = function (gradient) {
  52095. var y = Math.max(0.0, this.power);
  52096. return Math.pow(gradient, y);
  52097. };
  52098. return PowerEase;
  52099. }(EasingFunction));
  52100. BABYLON.PowerEase = PowerEase;
  52101. var QuadraticEase = /** @class */ (function (_super) {
  52102. __extends(QuadraticEase, _super);
  52103. function QuadraticEase() {
  52104. return _super !== null && _super.apply(this, arguments) || this;
  52105. }
  52106. QuadraticEase.prototype.easeInCore = function (gradient) {
  52107. return (gradient * gradient);
  52108. };
  52109. return QuadraticEase;
  52110. }(EasingFunction));
  52111. BABYLON.QuadraticEase = QuadraticEase;
  52112. var QuarticEase = /** @class */ (function (_super) {
  52113. __extends(QuarticEase, _super);
  52114. function QuarticEase() {
  52115. return _super !== null && _super.apply(this, arguments) || this;
  52116. }
  52117. QuarticEase.prototype.easeInCore = function (gradient) {
  52118. return (gradient * gradient * gradient * gradient);
  52119. };
  52120. return QuarticEase;
  52121. }(EasingFunction));
  52122. BABYLON.QuarticEase = QuarticEase;
  52123. var QuinticEase = /** @class */ (function (_super) {
  52124. __extends(QuinticEase, _super);
  52125. function QuinticEase() {
  52126. return _super !== null && _super.apply(this, arguments) || this;
  52127. }
  52128. QuinticEase.prototype.easeInCore = function (gradient) {
  52129. return (gradient * gradient * gradient * gradient * gradient);
  52130. };
  52131. return QuinticEase;
  52132. }(EasingFunction));
  52133. BABYLON.QuinticEase = QuinticEase;
  52134. var SineEase = /** @class */ (function (_super) {
  52135. __extends(SineEase, _super);
  52136. function SineEase() {
  52137. return _super !== null && _super.apply(this, arguments) || this;
  52138. }
  52139. SineEase.prototype.easeInCore = function (gradient) {
  52140. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52141. };
  52142. return SineEase;
  52143. }(EasingFunction));
  52144. BABYLON.SineEase = SineEase;
  52145. var BezierCurveEase = /** @class */ (function (_super) {
  52146. __extends(BezierCurveEase, _super);
  52147. function BezierCurveEase(x1, y1, x2, y2) {
  52148. if (x1 === void 0) { x1 = 0; }
  52149. if (y1 === void 0) { y1 = 0; }
  52150. if (x2 === void 0) { x2 = 1; }
  52151. if (y2 === void 0) { y2 = 1; }
  52152. var _this = _super.call(this) || this;
  52153. _this.x1 = x1;
  52154. _this.y1 = y1;
  52155. _this.x2 = x2;
  52156. _this.y2 = y2;
  52157. return _this;
  52158. }
  52159. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52160. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52161. };
  52162. return BezierCurveEase;
  52163. }(EasingFunction));
  52164. BABYLON.BezierCurveEase = BezierCurveEase;
  52165. })(BABYLON || (BABYLON = {}));
  52166. //# sourceMappingURL=babylon.easing.js.map
  52167. var BABYLON;
  52168. (function (BABYLON) {
  52169. /**
  52170. * A Condition applied to an Action
  52171. */
  52172. var Condition = /** @class */ (function () {
  52173. /**
  52174. * Creates a new Condition
  52175. * @param actionManager the manager of the action the condition is applied to
  52176. */
  52177. function Condition(actionManager) {
  52178. this._actionManager = actionManager;
  52179. }
  52180. /**
  52181. * Check if the current condition is valid
  52182. * @returns a boolean
  52183. */
  52184. Condition.prototype.isValid = function () {
  52185. return true;
  52186. };
  52187. /**
  52188. * Internal only
  52189. * @ignore
  52190. */
  52191. Condition.prototype._getProperty = function (propertyPath) {
  52192. return this._actionManager._getProperty(propertyPath);
  52193. };
  52194. /**
  52195. * Internal only
  52196. * @ignore
  52197. */
  52198. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52199. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52200. };
  52201. /**
  52202. * Serialize placeholder for child classes
  52203. * @returns the serialized object
  52204. */
  52205. Condition.prototype.serialize = function () {
  52206. };
  52207. /**
  52208. * Internal only
  52209. * @ignore
  52210. */
  52211. Condition.prototype._serialize = function (serializedCondition) {
  52212. return {
  52213. type: 2,
  52214. children: [],
  52215. name: serializedCondition.name,
  52216. properties: serializedCondition.properties
  52217. };
  52218. };
  52219. return Condition;
  52220. }());
  52221. BABYLON.Condition = Condition;
  52222. /**
  52223. * Defines specific conditional operators as extensions of Condition
  52224. */
  52225. var ValueCondition = /** @class */ (function (_super) {
  52226. __extends(ValueCondition, _super);
  52227. /**
  52228. * Creates a new ValueCondition
  52229. * @param actionManager manager for the action the condition applies to
  52230. * @param target for the action
  52231. * @param propertyPath path to specify the property of the target the conditional operator uses
  52232. * @param value the value compared by the conditional operator against the current value of the property
  52233. * @param operator the conditional operator, default ValueCondition.IsEqual
  52234. */
  52235. function ValueCondition(actionManager, target,
  52236. /** path to specify the property of the target the conditional operator uses */
  52237. propertyPath,
  52238. /** the value compared by the conditional operator against the current value of the property */
  52239. value,
  52240. /** the conditional operator, default ValueCondition.IsEqual */
  52241. operator) {
  52242. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52243. var _this = _super.call(this, actionManager) || this;
  52244. _this.propertyPath = propertyPath;
  52245. _this.value = value;
  52246. _this.operator = operator;
  52247. _this._target = target;
  52248. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52249. _this._property = _this._getProperty(_this.propertyPath);
  52250. return _this;
  52251. }
  52252. Object.defineProperty(ValueCondition, "IsEqual", {
  52253. /**
  52254. * returns the number for IsEqual
  52255. */
  52256. get: function () {
  52257. return ValueCondition._IsEqual;
  52258. },
  52259. enumerable: true,
  52260. configurable: true
  52261. });
  52262. Object.defineProperty(ValueCondition, "IsDifferent", {
  52263. /**
  52264. * Returns the number for IsDifferent
  52265. */
  52266. get: function () {
  52267. return ValueCondition._IsDifferent;
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. Object.defineProperty(ValueCondition, "IsGreater", {
  52273. /**
  52274. * Returns the number for IsGreater
  52275. */
  52276. get: function () {
  52277. return ValueCondition._IsGreater;
  52278. },
  52279. enumerable: true,
  52280. configurable: true
  52281. });
  52282. Object.defineProperty(ValueCondition, "IsLesser", {
  52283. /**
  52284. * Returns the number for IsLesser
  52285. */
  52286. get: function () {
  52287. return ValueCondition._IsLesser;
  52288. },
  52289. enumerable: true,
  52290. configurable: true
  52291. });
  52292. /**
  52293. * Compares the given value with the property value for the specified conditional operator
  52294. * @returns the result of the comparison
  52295. */
  52296. ValueCondition.prototype.isValid = function () {
  52297. switch (this.operator) {
  52298. case ValueCondition.IsGreater:
  52299. return this._effectiveTarget[this._property] > this.value;
  52300. case ValueCondition.IsLesser:
  52301. return this._effectiveTarget[this._property] < this.value;
  52302. case ValueCondition.IsEqual:
  52303. case ValueCondition.IsDifferent:
  52304. var check;
  52305. if (this.value.equals) {
  52306. check = this.value.equals(this._effectiveTarget[this._property]);
  52307. }
  52308. else {
  52309. check = this.value === this._effectiveTarget[this._property];
  52310. }
  52311. return this.operator === ValueCondition.IsEqual ? check : !check;
  52312. }
  52313. return false;
  52314. };
  52315. /**
  52316. * Serialize the ValueCondition into a JSON compatible object
  52317. * @returns serialization object
  52318. */
  52319. ValueCondition.prototype.serialize = function () {
  52320. return this._serialize({
  52321. name: "ValueCondition",
  52322. properties: [
  52323. BABYLON.Action._GetTargetProperty(this._target),
  52324. { name: "propertyPath", value: this.propertyPath },
  52325. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52326. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52327. ]
  52328. });
  52329. };
  52330. /**
  52331. * Gets the name of the conditional operator for the ValueCondition
  52332. * @param operator the conditional operator
  52333. * @returns the name
  52334. */
  52335. ValueCondition.GetOperatorName = function (operator) {
  52336. switch (operator) {
  52337. case ValueCondition._IsEqual: return "IsEqual";
  52338. case ValueCondition._IsDifferent: return "IsDifferent";
  52339. case ValueCondition._IsGreater: return "IsGreater";
  52340. case ValueCondition._IsLesser: return "IsLesser";
  52341. default: return "";
  52342. }
  52343. };
  52344. /**
  52345. * Internal only
  52346. * @ignore
  52347. */
  52348. ValueCondition._IsEqual = 0;
  52349. /**
  52350. * Internal only
  52351. * @ignore
  52352. */
  52353. ValueCondition._IsDifferent = 1;
  52354. /**
  52355. * Internal only
  52356. * @ignore
  52357. */
  52358. ValueCondition._IsGreater = 2;
  52359. /**
  52360. * Internal only
  52361. * @ignore
  52362. */
  52363. ValueCondition._IsLesser = 3;
  52364. return ValueCondition;
  52365. }(Condition));
  52366. BABYLON.ValueCondition = ValueCondition;
  52367. /**
  52368. * Defines a predicate condition as an extension of Condition
  52369. */
  52370. var PredicateCondition = /** @class */ (function (_super) {
  52371. __extends(PredicateCondition, _super);
  52372. /**
  52373. * Creates a new PredicateCondition
  52374. * @param actionManager manager for the action the condition applies to
  52375. * @param predicate defines the predicate function used to validate the condition
  52376. */
  52377. function PredicateCondition(actionManager,
  52378. /** defines the predicate function used to validate the condition */
  52379. predicate) {
  52380. var _this = _super.call(this, actionManager) || this;
  52381. _this.predicate = predicate;
  52382. return _this;
  52383. }
  52384. /**
  52385. * @returns the validity of the predicate condition
  52386. */
  52387. PredicateCondition.prototype.isValid = function () {
  52388. return this.predicate();
  52389. };
  52390. return PredicateCondition;
  52391. }(Condition));
  52392. BABYLON.PredicateCondition = PredicateCondition;
  52393. /**
  52394. * Defines a state condition as an extension of Condition
  52395. */
  52396. var StateCondition = /** @class */ (function (_super) {
  52397. __extends(StateCondition, _super);
  52398. /**
  52399. * Creates a new StateCondition
  52400. * @param actionManager manager for the action the condition applies to
  52401. * @param target of the condition
  52402. * @param value to compare with target state
  52403. */
  52404. function StateCondition(actionManager, target, value) {
  52405. var _this = _super.call(this, actionManager) || this;
  52406. _this.value = value;
  52407. _this._target = target;
  52408. return _this;
  52409. }
  52410. /**
  52411. * @returns the validity of the state
  52412. */
  52413. StateCondition.prototype.isValid = function () {
  52414. return this._target.state === this.value;
  52415. };
  52416. /**
  52417. * Serialize the StateCondition into a JSON compatible object
  52418. * @returns serialization object
  52419. */
  52420. StateCondition.prototype.serialize = function () {
  52421. return this._serialize({
  52422. name: "StateCondition",
  52423. properties: [
  52424. BABYLON.Action._GetTargetProperty(this._target),
  52425. { name: "value", value: this.value }
  52426. ]
  52427. });
  52428. };
  52429. return StateCondition;
  52430. }(Condition));
  52431. BABYLON.StateCondition = StateCondition;
  52432. })(BABYLON || (BABYLON = {}));
  52433. //# sourceMappingURL=babylon.condition.js.map
  52434. var BABYLON;
  52435. (function (BABYLON) {
  52436. /**
  52437. * The action to be carried out following a trigger
  52438. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52439. */
  52440. var Action = /** @class */ (function () {
  52441. /**
  52442. * Creates a new Action
  52443. * @param triggerOptions the trigger, with or without parameters, for the action
  52444. * @param condition an optional determinant of action
  52445. */
  52446. function Action(triggerOptions, condition) {
  52447. this.triggerOptions = triggerOptions;
  52448. /**
  52449. * An event triggered prior to action being executed.
  52450. */
  52451. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52452. if (triggerOptions.parameter) {
  52453. this.trigger = triggerOptions.trigger;
  52454. this._triggerParameter = triggerOptions.parameter;
  52455. }
  52456. else {
  52457. this.trigger = triggerOptions;
  52458. }
  52459. this._nextActiveAction = this;
  52460. this._condition = condition;
  52461. }
  52462. /**
  52463. * Internal only
  52464. * @ignore
  52465. */
  52466. Action.prototype._prepare = function () {
  52467. };
  52468. /**
  52469. * Gets the trigger parameters
  52470. * @returns the trigger parameters
  52471. */
  52472. Action.prototype.getTriggerParameter = function () {
  52473. return this._triggerParameter;
  52474. };
  52475. /**
  52476. * Internal only - executes current action event
  52477. * @ignore
  52478. */
  52479. Action.prototype._executeCurrent = function (evt) {
  52480. if (this._nextActiveAction._condition) {
  52481. var condition = this._nextActiveAction._condition;
  52482. var currentRenderId = this._actionManager.getScene().getRenderId();
  52483. // We cache the current evaluation for the current frame
  52484. if (condition._evaluationId === currentRenderId) {
  52485. if (!condition._currentResult) {
  52486. return;
  52487. }
  52488. }
  52489. else {
  52490. condition._evaluationId = currentRenderId;
  52491. if (!condition.isValid()) {
  52492. condition._currentResult = false;
  52493. return;
  52494. }
  52495. condition._currentResult = true;
  52496. }
  52497. }
  52498. this.onBeforeExecuteObservable.notifyObservers(this);
  52499. this._nextActiveAction.execute(evt);
  52500. this.skipToNextActiveAction();
  52501. };
  52502. /**
  52503. * Execute placeholder for child classes
  52504. * @param evt optional action event
  52505. */
  52506. Action.prototype.execute = function (evt) {
  52507. };
  52508. /**
  52509. * Skips to next active action
  52510. */
  52511. Action.prototype.skipToNextActiveAction = function () {
  52512. if (this._nextActiveAction._child) {
  52513. if (!this._nextActiveAction._child._actionManager) {
  52514. this._nextActiveAction._child._actionManager = this._actionManager;
  52515. }
  52516. this._nextActiveAction = this._nextActiveAction._child;
  52517. }
  52518. else {
  52519. this._nextActiveAction = this;
  52520. }
  52521. };
  52522. /**
  52523. * Adds action to chain of actions, may be a DoNothingAction
  52524. * @param index The index of the attribute.
  52525. * @returns The action passed in
  52526. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52527. */
  52528. Action.prototype.then = function (action) {
  52529. this._child = action;
  52530. action._actionManager = this._actionManager;
  52531. action._prepare();
  52532. return action;
  52533. };
  52534. /**
  52535. * Internal only
  52536. * @ignore
  52537. */
  52538. Action.prototype._getProperty = function (propertyPath) {
  52539. return this._actionManager._getProperty(propertyPath);
  52540. };
  52541. /**
  52542. * Internal only
  52543. * @ignore
  52544. */
  52545. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52546. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52547. };
  52548. /**
  52549. * Serialize placeholder for child classes
  52550. * @param parent of child
  52551. * @returns the serialized object
  52552. */
  52553. Action.prototype.serialize = function (parent) {
  52554. };
  52555. /**
  52556. * Internal only called by serialize
  52557. * @ignore
  52558. */
  52559. Action.prototype._serialize = function (serializedAction, parent) {
  52560. var serializationObject = {
  52561. type: 1,
  52562. children: [],
  52563. name: serializedAction.name,
  52564. properties: serializedAction.properties || []
  52565. };
  52566. // Serialize child
  52567. if (this._child) {
  52568. this._child.serialize(serializationObject);
  52569. }
  52570. // Check if "this" has a condition
  52571. if (this._condition) {
  52572. var serializedCondition = this._condition.serialize();
  52573. serializedCondition.children.push(serializationObject);
  52574. if (parent) {
  52575. parent.children.push(serializedCondition);
  52576. }
  52577. return serializedCondition;
  52578. }
  52579. if (parent) {
  52580. parent.children.push(serializationObject);
  52581. }
  52582. return serializationObject;
  52583. };
  52584. /**
  52585. * Internal only
  52586. * @ignore
  52587. */
  52588. Action._SerializeValueAsString = function (value) {
  52589. if (typeof value === "number") {
  52590. return value.toString();
  52591. }
  52592. if (typeof value === "boolean") {
  52593. return value ? "true" : "false";
  52594. }
  52595. if (value instanceof BABYLON.Vector2) {
  52596. return value.x + ", " + value.y;
  52597. }
  52598. if (value instanceof BABYLON.Vector3) {
  52599. return value.x + ", " + value.y + ", " + value.z;
  52600. }
  52601. if (value instanceof BABYLON.Color3) {
  52602. return value.r + ", " + value.g + ", " + value.b;
  52603. }
  52604. if (value instanceof BABYLON.Color4) {
  52605. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52606. }
  52607. return value; // string
  52608. };
  52609. /**
  52610. * Internal only
  52611. * @ignore
  52612. */
  52613. Action._GetTargetProperty = function (target) {
  52614. return {
  52615. name: "target",
  52616. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52617. : target instanceof BABYLON.Light ? "LightProperties"
  52618. : target instanceof BABYLON.Camera ? "CameraProperties"
  52619. : "SceneProperties",
  52620. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52621. };
  52622. };
  52623. return Action;
  52624. }());
  52625. BABYLON.Action = Action;
  52626. })(BABYLON || (BABYLON = {}));
  52627. //# sourceMappingURL=babylon.action.js.map
  52628. var BABYLON;
  52629. (function (BABYLON) {
  52630. /**
  52631. * ActionEvent is the event being sent when an action is triggered.
  52632. */
  52633. var ActionEvent = /** @class */ (function () {
  52634. /**
  52635. * @param source The mesh or sprite that triggered the action.
  52636. * @param pointerX The X mouse cursor position at the time of the event
  52637. * @param pointerY The Y mouse cursor position at the time of the event
  52638. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52639. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52640. */
  52641. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52642. this.source = source;
  52643. this.pointerX = pointerX;
  52644. this.pointerY = pointerY;
  52645. this.meshUnderPointer = meshUnderPointer;
  52646. this.sourceEvent = sourceEvent;
  52647. this.additionalData = additionalData;
  52648. }
  52649. /**
  52650. * Helper function to auto-create an ActionEvent from a source mesh.
  52651. * @param source The source mesh that triggered the event
  52652. * @param evt {Event} The original (browser) event
  52653. */
  52654. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52655. var scene = source.getScene();
  52656. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52657. };
  52658. /**
  52659. * Helper function to auto-create an ActionEvent from a source mesh.
  52660. * @param source The source sprite that triggered the event
  52661. * @param scene Scene associated with the sprite
  52662. * @param evt {Event} The original (browser) event
  52663. */
  52664. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52665. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52666. };
  52667. /**
  52668. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52669. * @param scene the scene where the event occurred
  52670. * @param evt {Event} The original (browser) event
  52671. */
  52672. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52673. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52674. };
  52675. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52676. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52677. };
  52678. return ActionEvent;
  52679. }());
  52680. BABYLON.ActionEvent = ActionEvent;
  52681. /**
  52682. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52683. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52684. */
  52685. var ActionManager = /** @class */ (function () {
  52686. function ActionManager(scene) {
  52687. // Members
  52688. this.actions = new Array();
  52689. this.hoverCursor = '';
  52690. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52691. scene._actionManagers.push(this);
  52692. }
  52693. Object.defineProperty(ActionManager, "NothingTrigger", {
  52694. get: function () {
  52695. return ActionManager._NothingTrigger;
  52696. },
  52697. enumerable: true,
  52698. configurable: true
  52699. });
  52700. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52701. get: function () {
  52702. return ActionManager._OnPickTrigger;
  52703. },
  52704. enumerable: true,
  52705. configurable: true
  52706. });
  52707. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52708. get: function () {
  52709. return ActionManager._OnLeftPickTrigger;
  52710. },
  52711. enumerable: true,
  52712. configurable: true
  52713. });
  52714. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52715. get: function () {
  52716. return ActionManager._OnRightPickTrigger;
  52717. },
  52718. enumerable: true,
  52719. configurable: true
  52720. });
  52721. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52722. get: function () {
  52723. return ActionManager._OnCenterPickTrigger;
  52724. },
  52725. enumerable: true,
  52726. configurable: true
  52727. });
  52728. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52729. get: function () {
  52730. return ActionManager._OnPickDownTrigger;
  52731. },
  52732. enumerable: true,
  52733. configurable: true
  52734. });
  52735. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52736. get: function () {
  52737. return ActionManager._OnDoublePickTrigger;
  52738. },
  52739. enumerable: true,
  52740. configurable: true
  52741. });
  52742. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52743. get: function () {
  52744. return ActionManager._OnPickUpTrigger;
  52745. },
  52746. enumerable: true,
  52747. configurable: true
  52748. });
  52749. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52750. /// This trigger will only be raised if you also declared a OnPickDown
  52751. get: function () {
  52752. return ActionManager._OnPickOutTrigger;
  52753. },
  52754. enumerable: true,
  52755. configurable: true
  52756. });
  52757. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52758. get: function () {
  52759. return ActionManager._OnLongPressTrigger;
  52760. },
  52761. enumerable: true,
  52762. configurable: true
  52763. });
  52764. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52765. get: function () {
  52766. return ActionManager._OnPointerOverTrigger;
  52767. },
  52768. enumerable: true,
  52769. configurable: true
  52770. });
  52771. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52772. get: function () {
  52773. return ActionManager._OnPointerOutTrigger;
  52774. },
  52775. enumerable: true,
  52776. configurable: true
  52777. });
  52778. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52779. get: function () {
  52780. return ActionManager._OnEveryFrameTrigger;
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52786. get: function () {
  52787. return ActionManager._OnIntersectionEnterTrigger;
  52788. },
  52789. enumerable: true,
  52790. configurable: true
  52791. });
  52792. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52793. get: function () {
  52794. return ActionManager._OnIntersectionExitTrigger;
  52795. },
  52796. enumerable: true,
  52797. configurable: true
  52798. });
  52799. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52800. get: function () {
  52801. return ActionManager._OnKeyDownTrigger;
  52802. },
  52803. enumerable: true,
  52804. configurable: true
  52805. });
  52806. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52807. get: function () {
  52808. return ActionManager._OnKeyUpTrigger;
  52809. },
  52810. enumerable: true,
  52811. configurable: true
  52812. });
  52813. // Methods
  52814. ActionManager.prototype.dispose = function () {
  52815. var index = this._scene._actionManagers.indexOf(this);
  52816. for (var i = 0; i < this.actions.length; i++) {
  52817. var action = this.actions[i];
  52818. ActionManager.Triggers[action.trigger]--;
  52819. if (ActionManager.Triggers[action.trigger] === 0) {
  52820. delete ActionManager.Triggers[action.trigger];
  52821. }
  52822. }
  52823. if (index > -1) {
  52824. this._scene._actionManagers.splice(index, 1);
  52825. }
  52826. };
  52827. ActionManager.prototype.getScene = function () {
  52828. return this._scene;
  52829. };
  52830. /**
  52831. * Does this action manager handles actions of any of the given triggers
  52832. * @param {number[]} triggers - the triggers to be tested
  52833. * @return {boolean} whether one (or more) of the triggers is handeled
  52834. */
  52835. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52836. for (var index = 0; index < this.actions.length; index++) {
  52837. var action = this.actions[index];
  52838. if (triggers.indexOf(action.trigger) > -1) {
  52839. return true;
  52840. }
  52841. }
  52842. return false;
  52843. };
  52844. /**
  52845. * Does this action manager handles actions of a given trigger
  52846. * @param trigger defines the trigger to be tested
  52847. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52848. * @return whether the trigger is handled
  52849. */
  52850. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52851. for (var index = 0; index < this.actions.length; index++) {
  52852. var action = this.actions[index];
  52853. if (action.trigger === trigger) {
  52854. if (parameterPredicate) {
  52855. if (parameterPredicate(action.getTriggerParameter())) {
  52856. return true;
  52857. }
  52858. }
  52859. else {
  52860. return true;
  52861. }
  52862. }
  52863. }
  52864. return false;
  52865. };
  52866. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52867. /**
  52868. * Does this action manager has pointer triggers
  52869. * @return {boolean} whether or not it has pointer triggers
  52870. */
  52871. get: function () {
  52872. for (var index = 0; index < this.actions.length; index++) {
  52873. var action = this.actions[index];
  52874. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52875. return true;
  52876. }
  52877. }
  52878. return false;
  52879. },
  52880. enumerable: true,
  52881. configurable: true
  52882. });
  52883. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52884. /**
  52885. * Does this action manager has pick triggers
  52886. * @return {boolean} whether or not it has pick triggers
  52887. */
  52888. get: function () {
  52889. for (var index = 0; index < this.actions.length; index++) {
  52890. var action = this.actions[index];
  52891. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52892. return true;
  52893. }
  52894. }
  52895. return false;
  52896. },
  52897. enumerable: true,
  52898. configurable: true
  52899. });
  52900. Object.defineProperty(ActionManager, "HasTriggers", {
  52901. /**
  52902. * Does exist one action manager with at least one trigger
  52903. * @return {boolean} whether or not it exists one action manager with one trigger
  52904. **/
  52905. get: function () {
  52906. for (var t in ActionManager.Triggers) {
  52907. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52908. return true;
  52909. }
  52910. }
  52911. return false;
  52912. },
  52913. enumerable: true,
  52914. configurable: true
  52915. });
  52916. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52917. /**
  52918. * Does exist one action manager with at least one pick trigger
  52919. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52920. **/
  52921. get: function () {
  52922. for (var t in ActionManager.Triggers) {
  52923. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52924. var t_int = parseInt(t);
  52925. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52926. return true;
  52927. }
  52928. }
  52929. }
  52930. return false;
  52931. },
  52932. enumerable: true,
  52933. configurable: true
  52934. });
  52935. /**
  52936. * Does exist one action manager that handles actions of a given trigger
  52937. * @param {number} trigger - the trigger to be tested
  52938. * @return {boolean} whether the trigger is handeled by at least one action manager
  52939. **/
  52940. ActionManager.HasSpecificTrigger = function (trigger) {
  52941. for (var t in ActionManager.Triggers) {
  52942. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52943. var t_int = parseInt(t);
  52944. if (t_int === trigger) {
  52945. return true;
  52946. }
  52947. }
  52948. }
  52949. return false;
  52950. };
  52951. /**
  52952. * Registers an action to this action manager
  52953. * @param {BABYLON.Action} action - the action to be registered
  52954. * @return {BABYLON.Action} the action amended (prepared) after registration
  52955. */
  52956. ActionManager.prototype.registerAction = function (action) {
  52957. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52958. if (this.getScene().actionManager !== this) {
  52959. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52960. return null;
  52961. }
  52962. }
  52963. this.actions.push(action);
  52964. if (ActionManager.Triggers[action.trigger]) {
  52965. ActionManager.Triggers[action.trigger]++;
  52966. }
  52967. else {
  52968. ActionManager.Triggers[action.trigger] = 1;
  52969. }
  52970. action._actionManager = this;
  52971. action._prepare();
  52972. return action;
  52973. };
  52974. /**
  52975. * Unregisters an action to this action manager
  52976. * @param action The action to be unregistered
  52977. * @return whether the action has been unregistered
  52978. */
  52979. ActionManager.prototype.unregisterAction = function (action) {
  52980. var index = this.actions.indexOf(action);
  52981. if (index !== -1) {
  52982. this.actions.splice(index, 1);
  52983. ActionManager.Triggers[action.trigger] -= 1;
  52984. if (ActionManager.Triggers[action.trigger] === 0) {
  52985. delete ActionManager.Triggers[action.trigger];
  52986. }
  52987. delete action._actionManager;
  52988. return true;
  52989. }
  52990. return false;
  52991. };
  52992. /**
  52993. * Process a specific trigger
  52994. * @param {number} trigger - the trigger to process
  52995. * @param evt {BABYLON.ActionEvent} the event details to be processed
  52996. */
  52997. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52998. for (var index = 0; index < this.actions.length; index++) {
  52999. var action = this.actions[index];
  53000. if (action.trigger === trigger) {
  53001. if (evt) {
  53002. if (trigger === ActionManager.OnKeyUpTrigger
  53003. || trigger === ActionManager.OnKeyDownTrigger) {
  53004. var parameter = action.getTriggerParameter();
  53005. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53006. if (!parameter.toLowerCase) {
  53007. continue;
  53008. }
  53009. var lowerCase = parameter.toLowerCase();
  53010. if (lowerCase !== evt.sourceEvent.key) {
  53011. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53012. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53013. if (actualkey !== lowerCase) {
  53014. continue;
  53015. }
  53016. }
  53017. }
  53018. }
  53019. }
  53020. action._executeCurrent(evt);
  53021. }
  53022. }
  53023. };
  53024. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53025. var properties = propertyPath.split(".");
  53026. for (var index = 0; index < properties.length - 1; index++) {
  53027. target = target[properties[index]];
  53028. }
  53029. return target;
  53030. };
  53031. ActionManager.prototype._getProperty = function (propertyPath) {
  53032. var properties = propertyPath.split(".");
  53033. return properties[properties.length - 1];
  53034. };
  53035. ActionManager.prototype.serialize = function (name) {
  53036. var root = {
  53037. children: new Array(),
  53038. name: name,
  53039. type: 3,
  53040. properties: new Array() // Empty for root but required
  53041. };
  53042. for (var i = 0; i < this.actions.length; i++) {
  53043. var triggerObject = {
  53044. type: 0,
  53045. children: new Array(),
  53046. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53047. properties: new Array()
  53048. };
  53049. var triggerOptions = this.actions[i].triggerOptions;
  53050. if (triggerOptions && typeof triggerOptions !== "number") {
  53051. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53052. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53053. }
  53054. else {
  53055. var parameter = {};
  53056. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53057. if (triggerOptions.parameter.mesh) {
  53058. parameter._meshId = triggerOptions.parameter.mesh.id;
  53059. }
  53060. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53061. }
  53062. }
  53063. // Serialize child action, recursively
  53064. this.actions[i].serialize(triggerObject);
  53065. // Add serialized trigger
  53066. root.children.push(triggerObject);
  53067. }
  53068. return root;
  53069. };
  53070. ActionManager.Parse = function (parsedActions, object, scene) {
  53071. var actionManager = new ActionManager(scene);
  53072. if (object === null)
  53073. scene.actionManager = actionManager;
  53074. else
  53075. object.actionManager = actionManager;
  53076. // instanciate a new object
  53077. var instanciate = function (name, params) {
  53078. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53079. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53080. newInstance.constructor.apply(newInstance, params);
  53081. return newInstance;
  53082. };
  53083. var parseParameter = function (name, value, target, propertyPath) {
  53084. if (propertyPath === null) {
  53085. // String, boolean or float
  53086. var floatValue = parseFloat(value);
  53087. if (value === "true" || value === "false")
  53088. return value === "true";
  53089. else
  53090. return isNaN(floatValue) ? value : floatValue;
  53091. }
  53092. var effectiveTarget = propertyPath.split(".");
  53093. var values = value.split(",");
  53094. // Get effective Target
  53095. for (var i = 0; i < effectiveTarget.length; i++) {
  53096. target = target[effectiveTarget[i]];
  53097. }
  53098. // Return appropriate value with its type
  53099. if (typeof (target) === "boolean")
  53100. return values[0] === "true";
  53101. if (typeof (target) === "string")
  53102. return values[0];
  53103. // Parameters with multiple values such as Vector3 etc.
  53104. var split = new Array();
  53105. for (var i = 0; i < values.length; i++)
  53106. split.push(parseFloat(values[i]));
  53107. if (target instanceof BABYLON.Vector3)
  53108. return BABYLON.Vector3.FromArray(split);
  53109. if (target instanceof BABYLON.Vector4)
  53110. return BABYLON.Vector4.FromArray(split);
  53111. if (target instanceof BABYLON.Color3)
  53112. return BABYLON.Color3.FromArray(split);
  53113. if (target instanceof BABYLON.Color4)
  53114. return BABYLON.Color4.FromArray(split);
  53115. return parseFloat(values[0]);
  53116. };
  53117. // traverse graph per trigger
  53118. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53119. if (combineArray === void 0) { combineArray = null; }
  53120. if (parsedAction.detached)
  53121. return;
  53122. var parameters = new Array();
  53123. var target = null;
  53124. var propertyPath = null;
  53125. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53126. // Parameters
  53127. if (parsedAction.type === 2)
  53128. parameters.push(actionManager);
  53129. else
  53130. parameters.push(trigger);
  53131. if (combine) {
  53132. var actions = new Array();
  53133. for (var j = 0; j < parsedAction.combine.length; j++) {
  53134. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53135. }
  53136. parameters.push(actions);
  53137. }
  53138. else {
  53139. for (var i = 0; i < parsedAction.properties.length; i++) {
  53140. var value = parsedAction.properties[i].value;
  53141. var name = parsedAction.properties[i].name;
  53142. var targetType = parsedAction.properties[i].targetType;
  53143. if (name === "target")
  53144. if (targetType !== null && targetType === "SceneProperties")
  53145. value = target = scene;
  53146. else
  53147. value = target = scene.getNodeByName(value);
  53148. else if (name === "parent")
  53149. value = scene.getNodeByName(value);
  53150. else if (name === "sound")
  53151. value = scene.getSoundByName(value);
  53152. else if (name !== "propertyPath") {
  53153. if (parsedAction.type === 2 && name === "operator")
  53154. value = BABYLON.ValueCondition[value];
  53155. else
  53156. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53157. }
  53158. else {
  53159. propertyPath = value;
  53160. }
  53161. parameters.push(value);
  53162. }
  53163. }
  53164. if (combineArray === null) {
  53165. parameters.push(condition);
  53166. }
  53167. else {
  53168. parameters.push(null);
  53169. }
  53170. // If interpolate value action
  53171. if (parsedAction.name === "InterpolateValueAction") {
  53172. var param = parameters[parameters.length - 2];
  53173. parameters[parameters.length - 1] = param;
  53174. parameters[parameters.length - 2] = condition;
  53175. }
  53176. // Action or condition(s) and not CombineAction
  53177. var newAction = instanciate(parsedAction.name, parameters);
  53178. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53179. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53180. if (action)
  53181. action.then(nothing);
  53182. else
  53183. actionManager.registerAction(nothing);
  53184. action = nothing;
  53185. }
  53186. if (combineArray === null) {
  53187. if (newAction instanceof BABYLON.Condition) {
  53188. condition = newAction;
  53189. newAction = action;
  53190. }
  53191. else {
  53192. condition = null;
  53193. if (action)
  53194. action.then(newAction);
  53195. else
  53196. actionManager.registerAction(newAction);
  53197. }
  53198. }
  53199. else {
  53200. combineArray.push(newAction);
  53201. }
  53202. for (var i = 0; i < parsedAction.children.length; i++)
  53203. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53204. };
  53205. // triggers
  53206. for (var i = 0; i < parsedActions.children.length; i++) {
  53207. var triggerParams;
  53208. var trigger = parsedActions.children[i];
  53209. if (trigger.properties.length > 0) {
  53210. var param = trigger.properties[0].value;
  53211. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53212. if (value._meshId) {
  53213. value.mesh = scene.getMeshByID(value._meshId);
  53214. }
  53215. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53216. }
  53217. else
  53218. triggerParams = ActionManager[trigger.name];
  53219. for (var j = 0; j < trigger.children.length; j++) {
  53220. if (!trigger.detached)
  53221. traverse(trigger.children[j], triggerParams, null, null);
  53222. }
  53223. }
  53224. };
  53225. ActionManager.GetTriggerName = function (trigger) {
  53226. switch (trigger) {
  53227. case 0: return "NothingTrigger";
  53228. case 1: return "OnPickTrigger";
  53229. case 2: return "OnLeftPickTrigger";
  53230. case 3: return "OnRightPickTrigger";
  53231. case 4: return "OnCenterPickTrigger";
  53232. case 5: return "OnPickDownTrigger";
  53233. case 6: return "OnPickUpTrigger";
  53234. case 7: return "OnLongPressTrigger";
  53235. case 8: return "OnPointerOverTrigger";
  53236. case 9: return "OnPointerOutTrigger";
  53237. case 10: return "OnEveryFrameTrigger";
  53238. case 11: return "OnIntersectionEnterTrigger";
  53239. case 12: return "OnIntersectionExitTrigger";
  53240. case 13: return "OnKeyDownTrigger";
  53241. case 14: return "OnKeyUpTrigger";
  53242. case 15: return "OnPickOutTrigger";
  53243. default: return "";
  53244. }
  53245. };
  53246. // Statics
  53247. ActionManager._NothingTrigger = 0;
  53248. ActionManager._OnPickTrigger = 1;
  53249. ActionManager._OnLeftPickTrigger = 2;
  53250. ActionManager._OnRightPickTrigger = 3;
  53251. ActionManager._OnCenterPickTrigger = 4;
  53252. ActionManager._OnPickDownTrigger = 5;
  53253. ActionManager._OnDoublePickTrigger = 6;
  53254. ActionManager._OnPickUpTrigger = 7;
  53255. ActionManager._OnLongPressTrigger = 8;
  53256. ActionManager._OnPointerOverTrigger = 9;
  53257. ActionManager._OnPointerOutTrigger = 10;
  53258. ActionManager._OnEveryFrameTrigger = 11;
  53259. ActionManager._OnIntersectionEnterTrigger = 12;
  53260. ActionManager._OnIntersectionExitTrigger = 13;
  53261. ActionManager._OnKeyDownTrigger = 14;
  53262. ActionManager._OnKeyUpTrigger = 15;
  53263. ActionManager._OnPickOutTrigger = 16;
  53264. ActionManager.Triggers = {};
  53265. return ActionManager;
  53266. }());
  53267. BABYLON.ActionManager = ActionManager;
  53268. })(BABYLON || (BABYLON = {}));
  53269. //# sourceMappingURL=babylon.actionManager.js.map
  53270. var BABYLON;
  53271. (function (BABYLON) {
  53272. var InterpolateValueAction = /** @class */ (function (_super) {
  53273. __extends(InterpolateValueAction, _super);
  53274. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53275. if (duration === void 0) { duration = 1000; }
  53276. var _this = _super.call(this, triggerOptions, condition) || this;
  53277. _this.propertyPath = propertyPath;
  53278. _this.value = value;
  53279. _this.duration = duration;
  53280. _this.stopOtherAnimations = stopOtherAnimations;
  53281. _this.onInterpolationDone = onInterpolationDone;
  53282. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53283. _this._target = _this._effectiveTarget = target;
  53284. return _this;
  53285. }
  53286. InterpolateValueAction.prototype._prepare = function () {
  53287. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53288. this._property = this._getProperty(this.propertyPath);
  53289. };
  53290. InterpolateValueAction.prototype.execute = function () {
  53291. var _this = this;
  53292. var scene = this._actionManager.getScene();
  53293. var keys = [
  53294. {
  53295. frame: 0,
  53296. value: this._effectiveTarget[this._property]
  53297. }, {
  53298. frame: 100,
  53299. value: this.value
  53300. }
  53301. ];
  53302. var dataType;
  53303. if (typeof this.value === "number") {
  53304. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53305. }
  53306. else if (this.value instanceof BABYLON.Color3) {
  53307. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53308. }
  53309. else if (this.value instanceof BABYLON.Vector3) {
  53310. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53311. }
  53312. else if (this.value instanceof BABYLON.Matrix) {
  53313. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53314. }
  53315. else if (this.value instanceof BABYLON.Quaternion) {
  53316. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53317. }
  53318. else {
  53319. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53320. return;
  53321. }
  53322. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53323. animation.setKeys(keys);
  53324. if (this.stopOtherAnimations) {
  53325. scene.stopAnimation(this._effectiveTarget);
  53326. }
  53327. var wrapper = function () {
  53328. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53329. if (_this.onInterpolationDone) {
  53330. _this.onInterpolationDone();
  53331. }
  53332. };
  53333. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53334. };
  53335. InterpolateValueAction.prototype.serialize = function (parent) {
  53336. return _super.prototype._serialize.call(this, {
  53337. name: "InterpolateValueAction",
  53338. properties: [
  53339. BABYLON.Action._GetTargetProperty(this._target),
  53340. { name: "propertyPath", value: this.propertyPath },
  53341. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53342. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53343. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53344. ]
  53345. }, parent);
  53346. };
  53347. return InterpolateValueAction;
  53348. }(BABYLON.Action));
  53349. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53350. })(BABYLON || (BABYLON = {}));
  53351. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53352. var BABYLON;
  53353. (function (BABYLON) {
  53354. var SwitchBooleanAction = /** @class */ (function (_super) {
  53355. __extends(SwitchBooleanAction, _super);
  53356. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53357. var _this = _super.call(this, triggerOptions, condition) || this;
  53358. _this.propertyPath = propertyPath;
  53359. _this._target = _this._effectiveTarget = target;
  53360. return _this;
  53361. }
  53362. SwitchBooleanAction.prototype._prepare = function () {
  53363. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53364. this._property = this._getProperty(this.propertyPath);
  53365. };
  53366. SwitchBooleanAction.prototype.execute = function () {
  53367. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53368. };
  53369. SwitchBooleanAction.prototype.serialize = function (parent) {
  53370. return _super.prototype._serialize.call(this, {
  53371. name: "SwitchBooleanAction",
  53372. properties: [
  53373. BABYLON.Action._GetTargetProperty(this._target),
  53374. { name: "propertyPath", value: this.propertyPath }
  53375. ]
  53376. }, parent);
  53377. };
  53378. return SwitchBooleanAction;
  53379. }(BABYLON.Action));
  53380. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53381. var SetStateAction = /** @class */ (function (_super) {
  53382. __extends(SetStateAction, _super);
  53383. function SetStateAction(triggerOptions, target, value, condition) {
  53384. var _this = _super.call(this, triggerOptions, condition) || this;
  53385. _this.value = value;
  53386. _this._target = target;
  53387. return _this;
  53388. }
  53389. SetStateAction.prototype.execute = function () {
  53390. this._target.state = this.value;
  53391. };
  53392. SetStateAction.prototype.serialize = function (parent) {
  53393. return _super.prototype._serialize.call(this, {
  53394. name: "SetStateAction",
  53395. properties: [
  53396. BABYLON.Action._GetTargetProperty(this._target),
  53397. { name: "value", value: this.value }
  53398. ]
  53399. }, parent);
  53400. };
  53401. return SetStateAction;
  53402. }(BABYLON.Action));
  53403. BABYLON.SetStateAction = SetStateAction;
  53404. var SetValueAction = /** @class */ (function (_super) {
  53405. __extends(SetValueAction, _super);
  53406. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53407. var _this = _super.call(this, triggerOptions, condition) || this;
  53408. _this.propertyPath = propertyPath;
  53409. _this.value = value;
  53410. _this._target = _this._effectiveTarget = target;
  53411. return _this;
  53412. }
  53413. SetValueAction.prototype._prepare = function () {
  53414. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53415. this._property = this._getProperty(this.propertyPath);
  53416. };
  53417. SetValueAction.prototype.execute = function () {
  53418. this._effectiveTarget[this._property] = this.value;
  53419. if (this._target.markAsDirty) {
  53420. this._target.markAsDirty(this._property);
  53421. }
  53422. };
  53423. SetValueAction.prototype.serialize = function (parent) {
  53424. return _super.prototype._serialize.call(this, {
  53425. name: "SetValueAction",
  53426. properties: [
  53427. BABYLON.Action._GetTargetProperty(this._target),
  53428. { name: "propertyPath", value: this.propertyPath },
  53429. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53430. ]
  53431. }, parent);
  53432. };
  53433. return SetValueAction;
  53434. }(BABYLON.Action));
  53435. BABYLON.SetValueAction = SetValueAction;
  53436. var IncrementValueAction = /** @class */ (function (_super) {
  53437. __extends(IncrementValueAction, _super);
  53438. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53439. var _this = _super.call(this, triggerOptions, condition) || this;
  53440. _this.propertyPath = propertyPath;
  53441. _this.value = value;
  53442. _this._target = _this._effectiveTarget = target;
  53443. return _this;
  53444. }
  53445. IncrementValueAction.prototype._prepare = function () {
  53446. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53447. this._property = this._getProperty(this.propertyPath);
  53448. if (typeof this._effectiveTarget[this._property] !== "number") {
  53449. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53450. }
  53451. };
  53452. IncrementValueAction.prototype.execute = function () {
  53453. this._effectiveTarget[this._property] += this.value;
  53454. if (this._target.markAsDirty) {
  53455. this._target.markAsDirty(this._property);
  53456. }
  53457. };
  53458. IncrementValueAction.prototype.serialize = function (parent) {
  53459. return _super.prototype._serialize.call(this, {
  53460. name: "IncrementValueAction",
  53461. properties: [
  53462. BABYLON.Action._GetTargetProperty(this._target),
  53463. { name: "propertyPath", value: this.propertyPath },
  53464. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53465. ]
  53466. }, parent);
  53467. };
  53468. return IncrementValueAction;
  53469. }(BABYLON.Action));
  53470. BABYLON.IncrementValueAction = IncrementValueAction;
  53471. var PlayAnimationAction = /** @class */ (function (_super) {
  53472. __extends(PlayAnimationAction, _super);
  53473. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53474. var _this = _super.call(this, triggerOptions, condition) || this;
  53475. _this.from = from;
  53476. _this.to = to;
  53477. _this.loop = loop;
  53478. _this._target = target;
  53479. return _this;
  53480. }
  53481. PlayAnimationAction.prototype._prepare = function () {
  53482. };
  53483. PlayAnimationAction.prototype.execute = function () {
  53484. var scene = this._actionManager.getScene();
  53485. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53486. };
  53487. PlayAnimationAction.prototype.serialize = function (parent) {
  53488. return _super.prototype._serialize.call(this, {
  53489. name: "PlayAnimationAction",
  53490. properties: [
  53491. BABYLON.Action._GetTargetProperty(this._target),
  53492. { name: "from", value: String(this.from) },
  53493. { name: "to", value: String(this.to) },
  53494. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53495. ]
  53496. }, parent);
  53497. };
  53498. return PlayAnimationAction;
  53499. }(BABYLON.Action));
  53500. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53501. var StopAnimationAction = /** @class */ (function (_super) {
  53502. __extends(StopAnimationAction, _super);
  53503. function StopAnimationAction(triggerOptions, target, condition) {
  53504. var _this = _super.call(this, triggerOptions, condition) || this;
  53505. _this._target = target;
  53506. return _this;
  53507. }
  53508. StopAnimationAction.prototype._prepare = function () {
  53509. };
  53510. StopAnimationAction.prototype.execute = function () {
  53511. var scene = this._actionManager.getScene();
  53512. scene.stopAnimation(this._target);
  53513. };
  53514. StopAnimationAction.prototype.serialize = function (parent) {
  53515. return _super.prototype._serialize.call(this, {
  53516. name: "StopAnimationAction",
  53517. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53518. }, parent);
  53519. };
  53520. return StopAnimationAction;
  53521. }(BABYLON.Action));
  53522. BABYLON.StopAnimationAction = StopAnimationAction;
  53523. var DoNothingAction = /** @class */ (function (_super) {
  53524. __extends(DoNothingAction, _super);
  53525. function DoNothingAction(triggerOptions, condition) {
  53526. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53527. return _super.call(this, triggerOptions, condition) || this;
  53528. }
  53529. DoNothingAction.prototype.execute = function () {
  53530. };
  53531. DoNothingAction.prototype.serialize = function (parent) {
  53532. return _super.prototype._serialize.call(this, {
  53533. name: "DoNothingAction",
  53534. properties: []
  53535. }, parent);
  53536. };
  53537. return DoNothingAction;
  53538. }(BABYLON.Action));
  53539. BABYLON.DoNothingAction = DoNothingAction;
  53540. var CombineAction = /** @class */ (function (_super) {
  53541. __extends(CombineAction, _super);
  53542. function CombineAction(triggerOptions, children, condition) {
  53543. var _this = _super.call(this, triggerOptions, condition) || this;
  53544. _this.children = children;
  53545. return _this;
  53546. }
  53547. CombineAction.prototype._prepare = function () {
  53548. for (var index = 0; index < this.children.length; index++) {
  53549. this.children[index]._actionManager = this._actionManager;
  53550. this.children[index]._prepare();
  53551. }
  53552. };
  53553. CombineAction.prototype.execute = function (evt) {
  53554. for (var index = 0; index < this.children.length; index++) {
  53555. this.children[index].execute(evt);
  53556. }
  53557. };
  53558. CombineAction.prototype.serialize = function (parent) {
  53559. var serializationObject = _super.prototype._serialize.call(this, {
  53560. name: "CombineAction",
  53561. properties: [],
  53562. combine: []
  53563. }, parent);
  53564. for (var i = 0; i < this.children.length; i++) {
  53565. serializationObject.combine.push(this.children[i].serialize(null));
  53566. }
  53567. return serializationObject;
  53568. };
  53569. return CombineAction;
  53570. }(BABYLON.Action));
  53571. BABYLON.CombineAction = CombineAction;
  53572. var ExecuteCodeAction = /** @class */ (function (_super) {
  53573. __extends(ExecuteCodeAction, _super);
  53574. function ExecuteCodeAction(triggerOptions, func, condition) {
  53575. var _this = _super.call(this, triggerOptions, condition) || this;
  53576. _this.func = func;
  53577. return _this;
  53578. }
  53579. ExecuteCodeAction.prototype.execute = function (evt) {
  53580. this.func(evt);
  53581. };
  53582. return ExecuteCodeAction;
  53583. }(BABYLON.Action));
  53584. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53585. var SetParentAction = /** @class */ (function (_super) {
  53586. __extends(SetParentAction, _super);
  53587. function SetParentAction(triggerOptions, target, parent, condition) {
  53588. var _this = _super.call(this, triggerOptions, condition) || this;
  53589. _this._target = target;
  53590. _this._parent = parent;
  53591. return _this;
  53592. }
  53593. SetParentAction.prototype._prepare = function () {
  53594. };
  53595. SetParentAction.prototype.execute = function () {
  53596. if (this._target.parent === this._parent) {
  53597. return;
  53598. }
  53599. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53600. invertParentWorldMatrix.invert();
  53601. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53602. this._target.parent = this._parent;
  53603. };
  53604. SetParentAction.prototype.serialize = function (parent) {
  53605. return _super.prototype._serialize.call(this, {
  53606. name: "SetParentAction",
  53607. properties: [
  53608. BABYLON.Action._GetTargetProperty(this._target),
  53609. BABYLON.Action._GetTargetProperty(this._parent),
  53610. ]
  53611. }, parent);
  53612. };
  53613. return SetParentAction;
  53614. }(BABYLON.Action));
  53615. BABYLON.SetParentAction = SetParentAction;
  53616. var PlaySoundAction = /** @class */ (function (_super) {
  53617. __extends(PlaySoundAction, _super);
  53618. function PlaySoundAction(triggerOptions, sound, condition) {
  53619. var _this = _super.call(this, triggerOptions, condition) || this;
  53620. _this._sound = sound;
  53621. return _this;
  53622. }
  53623. PlaySoundAction.prototype._prepare = function () {
  53624. };
  53625. PlaySoundAction.prototype.execute = function () {
  53626. if (this._sound !== undefined)
  53627. this._sound.play();
  53628. };
  53629. PlaySoundAction.prototype.serialize = function (parent) {
  53630. return _super.prototype._serialize.call(this, {
  53631. name: "PlaySoundAction",
  53632. properties: [{ name: "sound", value: this._sound.name }]
  53633. }, parent);
  53634. };
  53635. return PlaySoundAction;
  53636. }(BABYLON.Action));
  53637. BABYLON.PlaySoundAction = PlaySoundAction;
  53638. var StopSoundAction = /** @class */ (function (_super) {
  53639. __extends(StopSoundAction, _super);
  53640. function StopSoundAction(triggerOptions, sound, condition) {
  53641. var _this = _super.call(this, triggerOptions, condition) || this;
  53642. _this._sound = sound;
  53643. return _this;
  53644. }
  53645. StopSoundAction.prototype._prepare = function () {
  53646. };
  53647. StopSoundAction.prototype.execute = function () {
  53648. if (this._sound !== undefined)
  53649. this._sound.stop();
  53650. };
  53651. StopSoundAction.prototype.serialize = function (parent) {
  53652. return _super.prototype._serialize.call(this, {
  53653. name: "StopSoundAction",
  53654. properties: [{ name: "sound", value: this._sound.name }]
  53655. }, parent);
  53656. };
  53657. return StopSoundAction;
  53658. }(BABYLON.Action));
  53659. BABYLON.StopSoundAction = StopSoundAction;
  53660. })(BABYLON || (BABYLON = {}));
  53661. //# sourceMappingURL=babylon.directActions.js.map
  53662. var BABYLON;
  53663. (function (BABYLON) {
  53664. var SpriteManager = /** @class */ (function () {
  53665. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53666. if (epsilon === void 0) { epsilon = 0.01; }
  53667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53668. this.name = name;
  53669. this.sprites = new Array();
  53670. this.renderingGroupId = 0;
  53671. this.layerMask = 0x0FFFFFFF;
  53672. this.fogEnabled = true;
  53673. this.isPickable = false;
  53674. /**
  53675. * An event triggered when the manager is disposed.
  53676. */
  53677. this.onDisposeObservable = new BABYLON.Observable();
  53678. this._vertexBuffers = {};
  53679. this._capacity = capacity;
  53680. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53681. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53682. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53683. if (cellSize.width && cellSize.height) {
  53684. this.cellWidth = cellSize.width;
  53685. this.cellHeight = cellSize.height;
  53686. }
  53687. else if (cellSize !== undefined) {
  53688. this.cellWidth = cellSize;
  53689. this.cellHeight = cellSize;
  53690. }
  53691. else {
  53692. return;
  53693. }
  53694. this._epsilon = epsilon;
  53695. this._scene = scene;
  53696. this._scene.spriteManagers.push(this);
  53697. var indices = [];
  53698. var index = 0;
  53699. for (var count = 0; count < capacity; count++) {
  53700. indices.push(index);
  53701. indices.push(index + 1);
  53702. indices.push(index + 2);
  53703. indices.push(index);
  53704. indices.push(index + 2);
  53705. indices.push(index + 3);
  53706. index += 4;
  53707. }
  53708. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53709. // VBO
  53710. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53711. this._vertexData = new Float32Array(capacity * 16 * 4);
  53712. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53713. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53714. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53715. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53716. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53717. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53718. this._vertexBuffers["options"] = options;
  53719. this._vertexBuffers["cellInfo"] = cellInfo;
  53720. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53721. // Effects
  53722. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53723. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53724. }
  53725. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53726. set: function (callback) {
  53727. if (this._onDisposeObserver) {
  53728. this.onDisposeObservable.remove(this._onDisposeObserver);
  53729. }
  53730. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53731. },
  53732. enumerable: true,
  53733. configurable: true
  53734. });
  53735. Object.defineProperty(SpriteManager.prototype, "texture", {
  53736. get: function () {
  53737. return this._spriteTexture;
  53738. },
  53739. set: function (value) {
  53740. this._spriteTexture = value;
  53741. },
  53742. enumerable: true,
  53743. configurable: true
  53744. });
  53745. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53746. var arrayOffset = index * 16;
  53747. if (offsetX === 0)
  53748. offsetX = this._epsilon;
  53749. else if (offsetX === 1)
  53750. offsetX = 1 - this._epsilon;
  53751. if (offsetY === 0)
  53752. offsetY = this._epsilon;
  53753. else if (offsetY === 1)
  53754. offsetY = 1 - this._epsilon;
  53755. this._vertexData[arrayOffset] = sprite.position.x;
  53756. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53757. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53758. this._vertexData[arrayOffset + 3] = sprite.angle;
  53759. this._vertexData[arrayOffset + 4] = sprite.width;
  53760. this._vertexData[arrayOffset + 5] = sprite.height;
  53761. this._vertexData[arrayOffset + 6] = offsetX;
  53762. this._vertexData[arrayOffset + 7] = offsetY;
  53763. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53764. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53765. var offset = (sprite.cellIndex / rowSize) >> 0;
  53766. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53767. this._vertexData[arrayOffset + 11] = offset;
  53768. // Color
  53769. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53770. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53771. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53772. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53773. };
  53774. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53775. var count = Math.min(this._capacity, this.sprites.length);
  53776. var min = BABYLON.Vector3.Zero();
  53777. var max = BABYLON.Vector3.Zero();
  53778. var distance = Number.MAX_VALUE;
  53779. var currentSprite = null;
  53780. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53781. var cameraView = camera.getViewMatrix();
  53782. for (var index = 0; index < count; index++) {
  53783. var sprite = this.sprites[index];
  53784. if (!sprite) {
  53785. continue;
  53786. }
  53787. if (predicate) {
  53788. if (!predicate(sprite)) {
  53789. continue;
  53790. }
  53791. }
  53792. else if (!sprite.isPickable) {
  53793. continue;
  53794. }
  53795. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53796. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53797. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53798. if (ray.intersectsBoxMinMax(min, max)) {
  53799. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53800. if (distance > currentDistance) {
  53801. distance = currentDistance;
  53802. currentSprite = sprite;
  53803. if (fastCheck) {
  53804. break;
  53805. }
  53806. }
  53807. }
  53808. }
  53809. if (currentSprite) {
  53810. var result = new BABYLON.PickingInfo();
  53811. result.hit = true;
  53812. result.pickedSprite = currentSprite;
  53813. result.distance = distance;
  53814. return result;
  53815. }
  53816. return null;
  53817. };
  53818. SpriteManager.prototype.render = function () {
  53819. // Check
  53820. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53821. return;
  53822. var engine = this._scene.getEngine();
  53823. var baseSize = this._spriteTexture.getBaseSize();
  53824. // Sprites
  53825. var deltaTime = engine.getDeltaTime();
  53826. var max = Math.min(this._capacity, this.sprites.length);
  53827. var rowSize = baseSize.width / this.cellWidth;
  53828. var offset = 0;
  53829. for (var index = 0; index < max; index++) {
  53830. var sprite = this.sprites[index];
  53831. if (!sprite) {
  53832. continue;
  53833. }
  53834. sprite._animate(deltaTime);
  53835. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53836. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53837. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53838. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53839. }
  53840. this._buffer.update(this._vertexData);
  53841. // Render
  53842. var effect = this._effectBase;
  53843. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53844. effect = this._effectFog;
  53845. }
  53846. engine.enableEffect(effect);
  53847. var viewMatrix = this._scene.getViewMatrix();
  53848. effect.setTexture("diffuseSampler", this._spriteTexture);
  53849. effect.setMatrix("view", viewMatrix);
  53850. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53851. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53852. // Fog
  53853. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53854. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53855. effect.setColor3("vFogColor", this._scene.fogColor);
  53856. }
  53857. // VBOs
  53858. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53859. // Draw order
  53860. engine.setDepthFunctionToLessOrEqual();
  53861. effect.setBool("alphaTest", true);
  53862. engine.setColorWrite(false);
  53863. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53864. engine.setColorWrite(true);
  53865. effect.setBool("alphaTest", false);
  53866. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53867. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53868. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53869. };
  53870. SpriteManager.prototype.dispose = function () {
  53871. if (this._buffer) {
  53872. this._buffer.dispose();
  53873. this._buffer = null;
  53874. }
  53875. if (this._indexBuffer) {
  53876. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53877. this._indexBuffer = null;
  53878. }
  53879. if (this._spriteTexture) {
  53880. this._spriteTexture.dispose();
  53881. this._spriteTexture = null;
  53882. }
  53883. // Remove from scene
  53884. var index = this._scene.spriteManagers.indexOf(this);
  53885. this._scene.spriteManagers.splice(index, 1);
  53886. // Callback
  53887. this.onDisposeObservable.notifyObservers(this);
  53888. this.onDisposeObservable.clear();
  53889. };
  53890. return SpriteManager;
  53891. }());
  53892. BABYLON.SpriteManager = SpriteManager;
  53893. })(BABYLON || (BABYLON = {}));
  53894. //# sourceMappingURL=babylon.spriteManager.js.map
  53895. var BABYLON;
  53896. (function (BABYLON) {
  53897. var Sprite = /** @class */ (function () {
  53898. function Sprite(name, manager) {
  53899. this.name = name;
  53900. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53901. this.width = 1.0;
  53902. this.height = 1.0;
  53903. this.angle = 0;
  53904. this.cellIndex = 0;
  53905. this.invertU = 0;
  53906. this.invertV = 0;
  53907. this.animations = new Array();
  53908. this.isPickable = false;
  53909. this._animationStarted = false;
  53910. this._loopAnimation = false;
  53911. this._fromIndex = 0;
  53912. this._toIndex = 0;
  53913. this._delay = 0;
  53914. this._direction = 1;
  53915. this._time = 0;
  53916. this._manager = manager;
  53917. this._manager.sprites.push(this);
  53918. this.position = BABYLON.Vector3.Zero();
  53919. }
  53920. Object.defineProperty(Sprite.prototype, "size", {
  53921. get: function () {
  53922. return this.width;
  53923. },
  53924. set: function (value) {
  53925. this.width = value;
  53926. this.height = value;
  53927. },
  53928. enumerable: true,
  53929. configurable: true
  53930. });
  53931. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53932. this._fromIndex = from;
  53933. this._toIndex = to;
  53934. this._loopAnimation = loop;
  53935. this._delay = delay;
  53936. this._animationStarted = true;
  53937. this._direction = from < to ? 1 : -1;
  53938. this.cellIndex = from;
  53939. this._time = 0;
  53940. this._onAnimationEnd = onAnimationEnd;
  53941. };
  53942. Sprite.prototype.stopAnimation = function () {
  53943. this._animationStarted = false;
  53944. };
  53945. Sprite.prototype._animate = function (deltaTime) {
  53946. if (!this._animationStarted)
  53947. return;
  53948. this._time += deltaTime;
  53949. if (this._time > this._delay) {
  53950. this._time = this._time % this._delay;
  53951. this.cellIndex += this._direction;
  53952. if (this.cellIndex > this._toIndex) {
  53953. if (this._loopAnimation) {
  53954. this.cellIndex = this._fromIndex;
  53955. }
  53956. else {
  53957. this.cellIndex = this._toIndex;
  53958. this._animationStarted = false;
  53959. if (this._onAnimationEnd) {
  53960. this._onAnimationEnd();
  53961. }
  53962. if (this.disposeWhenFinishedAnimating) {
  53963. this.dispose();
  53964. }
  53965. }
  53966. }
  53967. }
  53968. };
  53969. Sprite.prototype.dispose = function () {
  53970. for (var i = 0; i < this._manager.sprites.length; i++) {
  53971. if (this._manager.sprites[i] == this) {
  53972. this._manager.sprites.splice(i, 1);
  53973. }
  53974. }
  53975. };
  53976. return Sprite;
  53977. }());
  53978. BABYLON.Sprite = Sprite;
  53979. })(BABYLON || (BABYLON = {}));
  53980. //# sourceMappingURL=babylon.sprite.js.map
  53981. var BABYLON;
  53982. (function (BABYLON) {
  53983. var IntersectionInfo = /** @class */ (function () {
  53984. function IntersectionInfo(bu, bv, distance) {
  53985. this.bu = bu;
  53986. this.bv = bv;
  53987. this.distance = distance;
  53988. this.faceId = 0;
  53989. this.subMeshId = 0;
  53990. }
  53991. return IntersectionInfo;
  53992. }());
  53993. BABYLON.IntersectionInfo = IntersectionInfo;
  53994. var PickingInfo = /** @class */ (function () {
  53995. function PickingInfo() {
  53996. this.hit = false;
  53997. this.distance = 0;
  53998. this.pickedPoint = null;
  53999. this.pickedMesh = null;
  54000. this.bu = 0;
  54001. this.bv = 0;
  54002. this.faceId = -1;
  54003. this.subMeshId = 0;
  54004. this.pickedSprite = null;
  54005. }
  54006. // Methods
  54007. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54008. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54009. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54010. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54011. return null;
  54012. }
  54013. var indices = this.pickedMesh.getIndices();
  54014. if (!indices) {
  54015. return null;
  54016. }
  54017. var result;
  54018. if (useVerticesNormals) {
  54019. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54020. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54021. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54022. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54023. normal0 = normal0.scale(this.bu);
  54024. normal1 = normal1.scale(this.bv);
  54025. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54026. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54027. }
  54028. else {
  54029. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54030. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54031. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54032. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54033. var p1p2 = vertex1.subtract(vertex2);
  54034. var p3p2 = vertex3.subtract(vertex2);
  54035. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54036. }
  54037. if (useWorldCoordinates) {
  54038. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54039. }
  54040. return BABYLON.Vector3.Normalize(result);
  54041. };
  54042. PickingInfo.prototype.getTextureCoordinates = function () {
  54043. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54044. return null;
  54045. }
  54046. var indices = this.pickedMesh.getIndices();
  54047. if (!indices) {
  54048. return null;
  54049. }
  54050. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54051. if (!uvs) {
  54052. return null;
  54053. }
  54054. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54055. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54056. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54057. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54058. uv1 = uv1.scale(this.bu);
  54059. uv2 = uv2.scale(this.bv);
  54060. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54061. };
  54062. return PickingInfo;
  54063. }());
  54064. BABYLON.PickingInfo = PickingInfo;
  54065. })(BABYLON || (BABYLON = {}));
  54066. //# sourceMappingURL=babylon.pickingInfo.js.map
  54067. var BABYLON;
  54068. (function (BABYLON) {
  54069. var Ray = /** @class */ (function () {
  54070. function Ray(origin, direction, length) {
  54071. if (length === void 0) { length = Number.MAX_VALUE; }
  54072. this.origin = origin;
  54073. this.direction = direction;
  54074. this.length = length;
  54075. }
  54076. // Methods
  54077. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54078. var d = 0.0;
  54079. var maxValue = Number.MAX_VALUE;
  54080. var inv;
  54081. var min;
  54082. var max;
  54083. var temp;
  54084. if (Math.abs(this.direction.x) < 0.0000001) {
  54085. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54086. return false;
  54087. }
  54088. }
  54089. else {
  54090. inv = 1.0 / this.direction.x;
  54091. min = (minimum.x - this.origin.x) * inv;
  54092. max = (maximum.x - this.origin.x) * inv;
  54093. if (max === -Infinity) {
  54094. max = Infinity;
  54095. }
  54096. if (min > max) {
  54097. temp = min;
  54098. min = max;
  54099. max = temp;
  54100. }
  54101. d = Math.max(min, d);
  54102. maxValue = Math.min(max, maxValue);
  54103. if (d > maxValue) {
  54104. return false;
  54105. }
  54106. }
  54107. if (Math.abs(this.direction.y) < 0.0000001) {
  54108. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54109. return false;
  54110. }
  54111. }
  54112. else {
  54113. inv = 1.0 / this.direction.y;
  54114. min = (minimum.y - this.origin.y) * inv;
  54115. max = (maximum.y - this.origin.y) * inv;
  54116. if (max === -Infinity) {
  54117. max = Infinity;
  54118. }
  54119. if (min > max) {
  54120. temp = min;
  54121. min = max;
  54122. max = temp;
  54123. }
  54124. d = Math.max(min, d);
  54125. maxValue = Math.min(max, maxValue);
  54126. if (d > maxValue) {
  54127. return false;
  54128. }
  54129. }
  54130. if (Math.abs(this.direction.z) < 0.0000001) {
  54131. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54132. return false;
  54133. }
  54134. }
  54135. else {
  54136. inv = 1.0 / this.direction.z;
  54137. min = (minimum.z - this.origin.z) * inv;
  54138. max = (maximum.z - this.origin.z) * inv;
  54139. if (max === -Infinity) {
  54140. max = Infinity;
  54141. }
  54142. if (min > max) {
  54143. temp = min;
  54144. min = max;
  54145. max = temp;
  54146. }
  54147. d = Math.max(min, d);
  54148. maxValue = Math.min(max, maxValue);
  54149. if (d > maxValue) {
  54150. return false;
  54151. }
  54152. }
  54153. return true;
  54154. };
  54155. Ray.prototype.intersectsBox = function (box) {
  54156. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54157. };
  54158. Ray.prototype.intersectsSphere = function (sphere) {
  54159. var x = sphere.center.x - this.origin.x;
  54160. var y = sphere.center.y - this.origin.y;
  54161. var z = sphere.center.z - this.origin.z;
  54162. var pyth = (x * x) + (y * y) + (z * z);
  54163. var rr = sphere.radius * sphere.radius;
  54164. if (pyth <= rr) {
  54165. return true;
  54166. }
  54167. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54168. if (dot < 0.0) {
  54169. return false;
  54170. }
  54171. var temp = pyth - (dot * dot);
  54172. return temp <= rr;
  54173. };
  54174. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54175. if (!this._edge1) {
  54176. this._edge1 = BABYLON.Vector3.Zero();
  54177. this._edge2 = BABYLON.Vector3.Zero();
  54178. this._pvec = BABYLON.Vector3.Zero();
  54179. this._tvec = BABYLON.Vector3.Zero();
  54180. this._qvec = BABYLON.Vector3.Zero();
  54181. }
  54182. vertex1.subtractToRef(vertex0, this._edge1);
  54183. vertex2.subtractToRef(vertex0, this._edge2);
  54184. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54185. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54186. if (det === 0) {
  54187. return null;
  54188. }
  54189. var invdet = 1 / det;
  54190. this.origin.subtractToRef(vertex0, this._tvec);
  54191. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54192. if (bu < 0 || bu > 1.0) {
  54193. return null;
  54194. }
  54195. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54196. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54197. if (bv < 0 || bu + bv > 1.0) {
  54198. return null;
  54199. }
  54200. //check if the distance is longer than the predefined length.
  54201. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54202. if (distance > this.length) {
  54203. return null;
  54204. }
  54205. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54206. };
  54207. Ray.prototype.intersectsPlane = function (plane) {
  54208. var distance;
  54209. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54210. if (Math.abs(result1) < 9.99999997475243E-07) {
  54211. return null;
  54212. }
  54213. else {
  54214. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54215. distance = (-plane.d - result2) / result1;
  54216. if (distance < 0.0) {
  54217. if (distance < -9.99999997475243E-07) {
  54218. return null;
  54219. }
  54220. else {
  54221. return 0;
  54222. }
  54223. }
  54224. return distance;
  54225. }
  54226. };
  54227. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54228. var tm = BABYLON.Tmp.Matrix[0];
  54229. mesh.getWorldMatrix().invertToRef(tm);
  54230. if (this._tmpRay) {
  54231. Ray.TransformToRef(this, tm, this._tmpRay);
  54232. }
  54233. else {
  54234. this._tmpRay = Ray.Transform(this, tm);
  54235. }
  54236. return mesh.intersects(this._tmpRay, fastCheck);
  54237. };
  54238. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54239. if (results) {
  54240. results.length = 0;
  54241. }
  54242. else {
  54243. results = [];
  54244. }
  54245. for (var i = 0; i < meshes.length; i++) {
  54246. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54247. if (pickInfo.hit) {
  54248. results.push(pickInfo);
  54249. }
  54250. }
  54251. results.sort(this._comparePickingInfo);
  54252. return results;
  54253. };
  54254. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54255. if (pickingInfoA.distance < pickingInfoB.distance) {
  54256. return -1;
  54257. }
  54258. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54259. return 1;
  54260. }
  54261. else {
  54262. return 0;
  54263. }
  54264. };
  54265. /**
  54266. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54267. * @param sega the first point of the segment to test the intersection against
  54268. * @param segb the second point of the segment to test the intersection against
  54269. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54270. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54271. */
  54272. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54273. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54274. var u = segb.subtract(sega);
  54275. var v = rsegb.subtract(this.origin);
  54276. var w = sega.subtract(this.origin);
  54277. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54278. var b = BABYLON.Vector3.Dot(u, v);
  54279. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54280. var d = BABYLON.Vector3.Dot(u, w);
  54281. var e = BABYLON.Vector3.Dot(v, w);
  54282. var D = a * c - b * b; // always >= 0
  54283. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54284. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54285. // compute the line parameters of the two closest points
  54286. if (D < Ray.smallnum) { // the lines are almost parallel
  54287. sN = 0.0; // force using point P0 on segment S1
  54288. sD = 1.0; // to prevent possible division by 0.0 later
  54289. tN = e;
  54290. tD = c;
  54291. }
  54292. else { // get the closest points on the infinite lines
  54293. sN = (b * e - c * d);
  54294. tN = (a * e - b * d);
  54295. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54296. sN = 0.0;
  54297. tN = e;
  54298. tD = c;
  54299. }
  54300. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54301. sN = sD;
  54302. tN = e + b;
  54303. tD = c;
  54304. }
  54305. }
  54306. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54307. tN = 0.0;
  54308. // recompute sc for this edge
  54309. if (-d < 0.0) {
  54310. sN = 0.0;
  54311. }
  54312. else if (-d > a)
  54313. sN = sD;
  54314. else {
  54315. sN = -d;
  54316. sD = a;
  54317. }
  54318. }
  54319. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54320. tN = tD;
  54321. // recompute sc for this edge
  54322. if ((-d + b) < 0.0) {
  54323. sN = 0;
  54324. }
  54325. else if ((-d + b) > a) {
  54326. sN = sD;
  54327. }
  54328. else {
  54329. sN = (-d + b);
  54330. sD = a;
  54331. }
  54332. }
  54333. // finally do the division to get sc and tc
  54334. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54335. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54336. // get the difference of the two closest points
  54337. var qtc = v.multiplyByFloats(tc, tc, tc);
  54338. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54339. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54340. if (isIntersected) {
  54341. return qtc.length();
  54342. }
  54343. return -1;
  54344. };
  54345. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54346. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54347. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54348. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54349. this.direction.normalize();
  54350. return this;
  54351. };
  54352. // Statics
  54353. Ray.Zero = function () {
  54354. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54355. };
  54356. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54357. var result = Ray.Zero();
  54358. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54359. };
  54360. /**
  54361. * 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
  54362. * transformed to the given world matrix.
  54363. * @param origin The origin point
  54364. * @param end The end point
  54365. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54366. */
  54367. Ray.CreateNewFromTo = function (origin, end, world) {
  54368. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54369. var direction = end.subtract(origin);
  54370. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54371. direction.normalize();
  54372. return Ray.Transform(new Ray(origin, direction, length), world);
  54373. };
  54374. Ray.Transform = function (ray, matrix) {
  54375. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54376. Ray.TransformToRef(ray, matrix, result);
  54377. return result;
  54378. };
  54379. Ray.TransformToRef = function (ray, matrix, result) {
  54380. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54381. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54382. result.length = ray.length;
  54383. var dir = result.direction;
  54384. var len = dir.length();
  54385. if (!(len === 0 || len === 1)) {
  54386. var num = 1.0 / len;
  54387. dir.x *= num;
  54388. dir.y *= num;
  54389. dir.z *= num;
  54390. result.length *= len;
  54391. }
  54392. };
  54393. Ray.smallnum = 0.00000001;
  54394. Ray.rayl = 10e8;
  54395. return Ray;
  54396. }());
  54397. BABYLON.Ray = Ray;
  54398. })(BABYLON || (BABYLON = {}));
  54399. //# sourceMappingURL=babylon.ray.js.map
  54400. var BABYLON;
  54401. (function (BABYLON) {
  54402. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54403. if (boxMin.x > sphereCenter.x + sphereRadius)
  54404. return false;
  54405. if (sphereCenter.x - sphereRadius > boxMax.x)
  54406. return false;
  54407. if (boxMin.y > sphereCenter.y + sphereRadius)
  54408. return false;
  54409. if (sphereCenter.y - sphereRadius > boxMax.y)
  54410. return false;
  54411. if (boxMin.z > sphereCenter.z + sphereRadius)
  54412. return false;
  54413. if (sphereCenter.z - sphereRadius > boxMax.z)
  54414. return false;
  54415. return true;
  54416. };
  54417. var getLowestRoot = (function () {
  54418. var result = { root: 0, found: false };
  54419. return function (a, b, c, maxR) {
  54420. result.root = 0;
  54421. result.found = false;
  54422. var determinant = b * b - 4.0 * a * c;
  54423. if (determinant < 0)
  54424. return result;
  54425. var sqrtD = Math.sqrt(determinant);
  54426. var r1 = (-b - sqrtD) / (2.0 * a);
  54427. var r2 = (-b + sqrtD) / (2.0 * a);
  54428. if (r1 > r2) {
  54429. var temp = r2;
  54430. r2 = r1;
  54431. r1 = temp;
  54432. }
  54433. if (r1 > 0 && r1 < maxR) {
  54434. result.root = r1;
  54435. result.found = true;
  54436. return result;
  54437. }
  54438. if (r2 > 0 && r2 < maxR) {
  54439. result.root = r2;
  54440. result.found = true;
  54441. return result;
  54442. }
  54443. return result;
  54444. };
  54445. })();
  54446. var Collider = /** @class */ (function () {
  54447. function Collider() {
  54448. this._collisionPoint = BABYLON.Vector3.Zero();
  54449. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54450. this._tempVector = BABYLON.Vector3.Zero();
  54451. this._tempVector2 = BABYLON.Vector3.Zero();
  54452. this._tempVector3 = BABYLON.Vector3.Zero();
  54453. this._tempVector4 = BABYLON.Vector3.Zero();
  54454. this._edge = BABYLON.Vector3.Zero();
  54455. this._baseToVertex = BABYLON.Vector3.Zero();
  54456. this._destinationPoint = BABYLON.Vector3.Zero();
  54457. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54458. this._displacementVector = BABYLON.Vector3.Zero();
  54459. this._radius = BABYLON.Vector3.One();
  54460. this._retry = 0;
  54461. this._basePointWorld = BABYLON.Vector3.Zero();
  54462. this._velocityWorld = BABYLON.Vector3.Zero();
  54463. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54464. this._collisionMask = -1;
  54465. }
  54466. Object.defineProperty(Collider.prototype, "collisionMask", {
  54467. get: function () {
  54468. return this._collisionMask;
  54469. },
  54470. set: function (mask) {
  54471. this._collisionMask = !isNaN(mask) ? mask : -1;
  54472. },
  54473. enumerable: true,
  54474. configurable: true
  54475. });
  54476. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54477. /**
  54478. * Gets the plane normal used to compute the sliding response (in local space)
  54479. */
  54480. get: function () {
  54481. return this._slidePlaneNormal;
  54482. },
  54483. enumerable: true,
  54484. configurable: true
  54485. });
  54486. // Methods
  54487. Collider.prototype._initialize = function (source, dir, e) {
  54488. this._velocity = dir;
  54489. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54490. this._basePoint = source;
  54491. source.multiplyToRef(this._radius, this._basePointWorld);
  54492. dir.multiplyToRef(this._radius, this._velocityWorld);
  54493. this._velocityWorldLength = this._velocityWorld.length();
  54494. this._epsilon = e;
  54495. this.collisionFound = false;
  54496. };
  54497. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54498. pa.subtractToRef(point, this._tempVector);
  54499. pb.subtractToRef(point, this._tempVector2);
  54500. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54501. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54502. if (d < 0)
  54503. return false;
  54504. pc.subtractToRef(point, this._tempVector3);
  54505. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54506. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54507. if (d < 0)
  54508. return false;
  54509. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54510. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54511. return d >= 0;
  54512. };
  54513. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54514. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54515. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54516. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54517. return false;
  54518. }
  54519. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54520. return false;
  54521. return true;
  54522. };
  54523. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54524. var t0;
  54525. var embeddedInPlane = false;
  54526. //defensive programming, actually not needed.
  54527. if (!trianglePlaneArray) {
  54528. trianglePlaneArray = [];
  54529. }
  54530. if (!trianglePlaneArray[faceIndex]) {
  54531. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54532. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54533. }
  54534. var trianglePlane = trianglePlaneArray[faceIndex];
  54535. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54536. return;
  54537. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54538. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54539. if (normalDotVelocity == 0) {
  54540. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54541. return;
  54542. embeddedInPlane = true;
  54543. t0 = 0;
  54544. }
  54545. else {
  54546. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54547. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54548. if (t0 > t1) {
  54549. var temp = t1;
  54550. t1 = t0;
  54551. t0 = temp;
  54552. }
  54553. if (t0 > 1.0 || t1 < 0.0)
  54554. return;
  54555. if (t0 < 0)
  54556. t0 = 0;
  54557. if (t0 > 1.0)
  54558. t0 = 1.0;
  54559. }
  54560. this._collisionPoint.copyFromFloats(0, 0, 0);
  54561. var found = false;
  54562. var t = 1.0;
  54563. if (!embeddedInPlane) {
  54564. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54565. this._velocity.scaleToRef(t0, this._tempVector);
  54566. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54567. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54568. found = true;
  54569. t = t0;
  54570. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54571. }
  54572. }
  54573. if (!found) {
  54574. var velocitySquaredLength = this._velocity.lengthSquared();
  54575. var a = velocitySquaredLength;
  54576. this._basePoint.subtractToRef(p1, this._tempVector);
  54577. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54578. var c = this._tempVector.lengthSquared() - 1.0;
  54579. var lowestRoot = getLowestRoot(a, b, c, t);
  54580. if (lowestRoot.found) {
  54581. t = lowestRoot.root;
  54582. found = true;
  54583. this._collisionPoint.copyFrom(p1);
  54584. }
  54585. this._basePoint.subtractToRef(p2, this._tempVector);
  54586. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54587. c = this._tempVector.lengthSquared() - 1.0;
  54588. lowestRoot = getLowestRoot(a, b, c, t);
  54589. if (lowestRoot.found) {
  54590. t = lowestRoot.root;
  54591. found = true;
  54592. this._collisionPoint.copyFrom(p2);
  54593. }
  54594. this._basePoint.subtractToRef(p3, this._tempVector);
  54595. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54596. c = this._tempVector.lengthSquared() - 1.0;
  54597. lowestRoot = getLowestRoot(a, b, c, t);
  54598. if (lowestRoot.found) {
  54599. t = lowestRoot.root;
  54600. found = true;
  54601. this._collisionPoint.copyFrom(p3);
  54602. }
  54603. p2.subtractToRef(p1, this._edge);
  54604. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54605. var edgeSquaredLength = this._edge.lengthSquared();
  54606. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54607. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54608. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54609. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54610. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54611. lowestRoot = getLowestRoot(a, b, c, t);
  54612. if (lowestRoot.found) {
  54613. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54614. if (f >= 0.0 && f <= 1.0) {
  54615. t = lowestRoot.root;
  54616. found = true;
  54617. this._edge.scaleInPlace(f);
  54618. p1.addToRef(this._edge, this._collisionPoint);
  54619. }
  54620. }
  54621. p3.subtractToRef(p2, this._edge);
  54622. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54623. edgeSquaredLength = this._edge.lengthSquared();
  54624. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54625. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54626. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54627. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54628. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54629. lowestRoot = getLowestRoot(a, b, c, t);
  54630. if (lowestRoot.found) {
  54631. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54632. if (f >= 0.0 && f <= 1.0) {
  54633. t = lowestRoot.root;
  54634. found = true;
  54635. this._edge.scaleInPlace(f);
  54636. p2.addToRef(this._edge, this._collisionPoint);
  54637. }
  54638. }
  54639. p1.subtractToRef(p3, this._edge);
  54640. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54641. edgeSquaredLength = this._edge.lengthSquared();
  54642. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54643. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54644. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54645. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54646. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54647. lowestRoot = getLowestRoot(a, b, c, t);
  54648. if (lowestRoot.found) {
  54649. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54650. if (f >= 0.0 && f <= 1.0) {
  54651. t = lowestRoot.root;
  54652. found = true;
  54653. this._edge.scaleInPlace(f);
  54654. p3.addToRef(this._edge, this._collisionPoint);
  54655. }
  54656. }
  54657. }
  54658. if (found) {
  54659. var distToCollision = t * this._velocity.length();
  54660. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54661. if (!this.intersectionPoint) {
  54662. this.intersectionPoint = this._collisionPoint.clone();
  54663. }
  54664. else {
  54665. this.intersectionPoint.copyFrom(this._collisionPoint);
  54666. }
  54667. this._nearestDistance = distToCollision;
  54668. this.collisionFound = true;
  54669. }
  54670. }
  54671. };
  54672. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54673. for (var i = indexStart; i < indexEnd; i += 3) {
  54674. var p1 = pts[indices[i] - decal];
  54675. var p2 = pts[indices[i + 1] - decal];
  54676. var p3 = pts[indices[i + 2] - decal];
  54677. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54678. }
  54679. };
  54680. Collider.prototype._getResponse = function (pos, vel) {
  54681. pos.addToRef(vel, this._destinationPoint);
  54682. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54683. this._basePoint.addToRef(vel, pos);
  54684. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54685. this._slidePlaneNormal.normalize();
  54686. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54687. pos.addInPlace(this._displacementVector);
  54688. this.intersectionPoint.addInPlace(this._displacementVector);
  54689. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54690. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54691. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54692. };
  54693. return Collider;
  54694. }());
  54695. BABYLON.Collider = Collider;
  54696. })(BABYLON || (BABYLON = {}));
  54697. //# sourceMappingURL=babylon.collider.js.map
  54698. var BABYLON;
  54699. (function (BABYLON) {
  54700. //WebWorker code will be inserted to this variable.
  54701. BABYLON.CollisionWorker = "";
  54702. var WorkerTaskType;
  54703. (function (WorkerTaskType) {
  54704. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54705. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54706. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54707. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54708. var WorkerReplyType;
  54709. (function (WorkerReplyType) {
  54710. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54711. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54712. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54713. var CollisionCoordinatorWorker = /** @class */ (function () {
  54714. function CollisionCoordinatorWorker() {
  54715. var _this = this;
  54716. this._scaledPosition = BABYLON.Vector3.Zero();
  54717. this._scaledVelocity = BABYLON.Vector3.Zero();
  54718. this.onMeshUpdated = function (transformNode) {
  54719. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54720. };
  54721. this.onGeometryUpdated = function (geometry) {
  54722. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54723. };
  54724. this._afterRender = function () {
  54725. if (!_this._init)
  54726. return;
  54727. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54728. return;
  54729. }
  54730. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54731. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54732. if (_this._runningUpdated > 4) {
  54733. return;
  54734. }
  54735. ++_this._runningUpdated;
  54736. var payload = {
  54737. updatedMeshes: _this._addUpdateMeshesList,
  54738. updatedGeometries: _this._addUpdateGeometriesList,
  54739. removedGeometries: _this._toRemoveGeometryArray,
  54740. removedMeshes: _this._toRemoveMeshesArray
  54741. };
  54742. var message = {
  54743. payload: payload,
  54744. taskType: WorkerTaskType.UPDATE
  54745. };
  54746. var serializable = [];
  54747. for (var id in payload.updatedGeometries) {
  54748. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54749. //prepare transferables
  54750. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54751. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54752. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54753. }
  54754. }
  54755. _this._worker.postMessage(message, serializable);
  54756. _this._addUpdateMeshesList = {};
  54757. _this._addUpdateGeometriesList = {};
  54758. _this._toRemoveGeometryArray = [];
  54759. _this._toRemoveMeshesArray = [];
  54760. };
  54761. this._onMessageFromWorker = function (e) {
  54762. var returnData = e.data;
  54763. if (returnData.error != WorkerReplyType.SUCCESS) {
  54764. //TODO what errors can be returned from the worker?
  54765. BABYLON.Tools.Warn("error returned from worker!");
  54766. return;
  54767. }
  54768. switch (returnData.taskType) {
  54769. case WorkerTaskType.INIT:
  54770. _this._init = true;
  54771. //Update the worked with ALL of the scene's current state
  54772. _this._scene.meshes.forEach(function (mesh) {
  54773. _this.onMeshAdded(mesh);
  54774. });
  54775. _this._scene.getGeometries().forEach(function (geometry) {
  54776. _this.onGeometryAdded(geometry);
  54777. });
  54778. break;
  54779. case WorkerTaskType.UPDATE:
  54780. _this._runningUpdated--;
  54781. break;
  54782. case WorkerTaskType.COLLIDE:
  54783. var returnPayload = returnData.payload;
  54784. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54785. return;
  54786. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54787. if (callback) {
  54788. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54789. if (mesh) {
  54790. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54791. }
  54792. }
  54793. //cleanup
  54794. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54795. break;
  54796. }
  54797. };
  54798. this._collisionsCallbackArray = [];
  54799. this._init = false;
  54800. this._runningUpdated = 0;
  54801. this._addUpdateMeshesList = {};
  54802. this._addUpdateGeometriesList = {};
  54803. this._toRemoveGeometryArray = [];
  54804. this._toRemoveMeshesArray = [];
  54805. }
  54806. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54807. if (!this._init)
  54808. return;
  54809. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54810. return;
  54811. position.divideToRef(collider._radius, this._scaledPosition);
  54812. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54813. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54814. var payload = {
  54815. collider: {
  54816. position: this._scaledPosition.asArray(),
  54817. velocity: this._scaledVelocity.asArray(),
  54818. radius: collider._radius.asArray()
  54819. },
  54820. collisionId: collisionIndex,
  54821. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54822. maximumRetry: maximumRetry
  54823. };
  54824. var message = {
  54825. payload: payload,
  54826. taskType: WorkerTaskType.COLLIDE
  54827. };
  54828. this._worker.postMessage(message);
  54829. };
  54830. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54831. this._scene = scene;
  54832. this._scene.registerAfterRender(this._afterRender);
  54833. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54834. this._worker = new Worker(workerUrl);
  54835. this._worker.onmessage = this._onMessageFromWorker;
  54836. var message = {
  54837. payload: {},
  54838. taskType: WorkerTaskType.INIT
  54839. };
  54840. this._worker.postMessage(message);
  54841. };
  54842. CollisionCoordinatorWorker.prototype.destroy = function () {
  54843. this._scene.unregisterAfterRender(this._afterRender);
  54844. this._worker.terminate();
  54845. };
  54846. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54847. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54848. this.onMeshUpdated(mesh);
  54849. };
  54850. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54851. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54852. };
  54853. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54854. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54855. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54856. this.onGeometryUpdated(geometry);
  54857. };
  54858. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54859. this._toRemoveGeometryArray.push(geometry.id);
  54860. };
  54861. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54862. var submeshes = [];
  54863. if (mesh.subMeshes) {
  54864. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54865. var boundingInfo = sm.getBoundingInfo();
  54866. return {
  54867. position: idx,
  54868. verticesStart: sm.verticesStart,
  54869. verticesCount: sm.verticesCount,
  54870. indexStart: sm.indexStart,
  54871. indexCount: sm.indexCount,
  54872. hasMaterial: !!sm.getMaterial(),
  54873. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54874. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54875. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54876. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54877. };
  54878. });
  54879. }
  54880. var geometryId = null;
  54881. if (mesh instanceof BABYLON.Mesh) {
  54882. var geometry = mesh.geometry;
  54883. geometryId = geometry ? geometry.id : null;
  54884. }
  54885. else if (mesh instanceof BABYLON.InstancedMesh) {
  54886. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54887. geometryId = geometry ? geometry.id : null;
  54888. }
  54889. var boundingInfo = mesh.getBoundingInfo();
  54890. return {
  54891. uniqueId: mesh.uniqueId,
  54892. id: mesh.id,
  54893. name: mesh.name,
  54894. geometryId: geometryId,
  54895. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54896. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54897. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54898. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54899. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54900. subMeshes: submeshes,
  54901. checkCollisions: mesh.checkCollisions
  54902. };
  54903. };
  54904. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54905. return {
  54906. id: geometry.id,
  54907. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54908. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54909. indices: new Uint32Array(geometry.getIndices() || []),
  54910. };
  54911. };
  54912. return CollisionCoordinatorWorker;
  54913. }());
  54914. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54915. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54916. function CollisionCoordinatorLegacy() {
  54917. this._scaledPosition = BABYLON.Vector3.Zero();
  54918. this._scaledVelocity = BABYLON.Vector3.Zero();
  54919. this._finalPosition = BABYLON.Vector3.Zero();
  54920. }
  54921. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54922. position.divideToRef(collider._radius, this._scaledPosition);
  54923. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54924. collider.collidedMesh = null;
  54925. collider._retry = 0;
  54926. collider._initialVelocity = this._scaledVelocity;
  54927. collider._initialPosition = this._scaledPosition;
  54928. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54929. this._finalPosition.multiplyInPlace(collider._radius);
  54930. //run the callback
  54931. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54932. };
  54933. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54934. this._scene = scene;
  54935. };
  54936. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54937. //Legacy need no destruction method.
  54938. };
  54939. //No update in legacy mode
  54940. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54941. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54942. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54943. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54944. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54945. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54946. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54947. if (excludedMesh === void 0) { excludedMesh = null; }
  54948. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54949. if (collider._retry >= maximumRetry) {
  54950. finalPosition.copyFrom(position);
  54951. return;
  54952. }
  54953. // Check if this is a mesh else camera or -1
  54954. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54955. collider._initialize(position, velocity, closeDistance);
  54956. // Check all meshes
  54957. for (var index = 0; index < this._scene.meshes.length; index++) {
  54958. var mesh = this._scene.meshes[index];
  54959. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54960. mesh._checkCollision(collider);
  54961. }
  54962. }
  54963. if (!collider.collisionFound) {
  54964. position.addToRef(velocity, finalPosition);
  54965. return;
  54966. }
  54967. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54968. collider._getResponse(position, velocity);
  54969. }
  54970. if (velocity.length() <= closeDistance) {
  54971. finalPosition.copyFrom(position);
  54972. return;
  54973. }
  54974. collider._retry++;
  54975. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54976. };
  54977. return CollisionCoordinatorLegacy;
  54978. }());
  54979. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54980. })(BABYLON || (BABYLON = {}));
  54981. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54982. var BABYLON;
  54983. (function (BABYLON) {
  54984. /**
  54985. * A particle represents one of the element emitted by a particle system.
  54986. * This is mainly define by its coordinates, direction, velocity and age.
  54987. */
  54988. var Particle = /** @class */ (function () {
  54989. /**
  54990. * Creates a new instance Particle
  54991. * @param particleSystem the particle system the particle belongs to
  54992. */
  54993. function Particle(
  54994. /**
  54995. * particleSystem the particle system the particle belongs to.
  54996. */
  54997. particleSystem) {
  54998. this.particleSystem = particleSystem;
  54999. /**
  55000. * The world position of the particle in the scene.
  55001. */
  55002. this.position = BABYLON.Vector3.Zero();
  55003. /**
  55004. * The world direction of the particle in the scene.
  55005. */
  55006. this.direction = BABYLON.Vector3.Zero();
  55007. /**
  55008. * The color of the particle.
  55009. */
  55010. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55011. /**
  55012. * The color change of the particle per step.
  55013. */
  55014. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55015. /**
  55016. * Defines how long will the life of the particle be.
  55017. */
  55018. this.lifeTime = 1.0;
  55019. /**
  55020. * The current age of the particle.
  55021. */
  55022. this.age = 0;
  55023. /**
  55024. * The current size of the particle.
  55025. */
  55026. this.size = 0;
  55027. /**
  55028. * The current angle of the particle.
  55029. */
  55030. this.angle = 0;
  55031. /**
  55032. * Defines how fast is the angle changing.
  55033. */
  55034. this.angularSpeed = 0;
  55035. /**
  55036. * Defines the cell index used by the particle to be rendered from a sprite.
  55037. */
  55038. this.cellIndex = 0;
  55039. this._currentFrameCounter = 0;
  55040. if (!this.particleSystem.isAnimationSheetEnabled) {
  55041. return;
  55042. }
  55043. this.updateCellInfoFromSystem();
  55044. }
  55045. Particle.prototype.updateCellInfoFromSystem = function () {
  55046. this.cellIndex = this.particleSystem.startSpriteCellID;
  55047. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55048. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55049. }
  55050. else {
  55051. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55052. }
  55053. };
  55054. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55055. // (ageOffset / scaledUpdateSpeed) / available cells
  55056. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55057. this._currentFrameCounter += scaledUpdateSpeed;
  55058. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55059. this._currentFrameCounter = 0;
  55060. this.cellIndex++;
  55061. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55062. this.cellIndex = this.particleSystem.endSpriteCellID;
  55063. }
  55064. }
  55065. };
  55066. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55067. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55068. this.cellIndex++;
  55069. this._currentFrameCounter = 0;
  55070. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55071. if (this.particleSystem.spriteCellLoop) {
  55072. this.cellIndex = this.particleSystem.startSpriteCellID;
  55073. }
  55074. else {
  55075. this.cellIndex = this.particleSystem.endSpriteCellID;
  55076. }
  55077. }
  55078. }
  55079. else {
  55080. this._currentFrameCounter++;
  55081. }
  55082. };
  55083. /**
  55084. * Copy the properties of particle to another one.
  55085. * @param other the particle to copy the information to.
  55086. */
  55087. Particle.prototype.copyTo = function (other) {
  55088. other.position.copyFrom(this.position);
  55089. other.direction.copyFrom(this.direction);
  55090. other.color.copyFrom(this.color);
  55091. other.colorStep.copyFrom(this.colorStep);
  55092. other.lifeTime = this.lifeTime;
  55093. other.age = this.age;
  55094. other.size = this.size;
  55095. other.angle = this.angle;
  55096. other.angularSpeed = this.angularSpeed;
  55097. other.particleSystem = this.particleSystem;
  55098. other.cellIndex = this.cellIndex;
  55099. };
  55100. return Particle;
  55101. }());
  55102. BABYLON.Particle = Particle;
  55103. })(BABYLON || (BABYLON = {}));
  55104. //# sourceMappingURL=babylon.particle.js.map
  55105. var BABYLON;
  55106. (function (BABYLON) {
  55107. /**
  55108. * This represents a particle system in Babylon.
  55109. * 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.
  55110. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55111. * @example https://doc.babylonjs.com/babylon101/particles
  55112. */
  55113. var ParticleSystem = /** @class */ (function () {
  55114. /**
  55115. * Instantiates a particle system.
  55116. * 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.
  55117. * @param name The name of the particle system
  55118. * @param capacity The max number of particles alive at the same time
  55119. * @param scene The scene the particle system belongs to
  55120. * @param customEffect a custom effect used to change the way particles are rendered by default
  55121. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55122. * @param epsilon Offset used to render the particles
  55123. */
  55124. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55125. if (customEffect === void 0) { customEffect = null; }
  55126. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55127. if (epsilon === void 0) { epsilon = 0.01; }
  55128. var _this = this;
  55129. /**
  55130. * List of animations used by the particle system.
  55131. */
  55132. this.animations = [];
  55133. /**
  55134. * The rendering group used by the Particle system to chose when to render.
  55135. */
  55136. this.renderingGroupId = 0;
  55137. /**
  55138. * The emitter represents the Mesh or position we are attaching the particle system to.
  55139. */
  55140. this.emitter = null;
  55141. /**
  55142. * The maximum number of particles to emit per frame
  55143. */
  55144. this.emitRate = 10;
  55145. /**
  55146. * If you want to launch only a few particles at once, that can be done, as well.
  55147. */
  55148. this.manualEmitCount = -1;
  55149. /**
  55150. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55151. */
  55152. this.updateSpeed = 0.01;
  55153. /**
  55154. * The amount of time the particle system is running (depends of the overall update speed).
  55155. */
  55156. this.targetStopDuration = 0;
  55157. /**
  55158. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55159. */
  55160. this.disposeOnStop = false;
  55161. /**
  55162. * Minimum power of emitting particles.
  55163. */
  55164. this.minEmitPower = 1;
  55165. /**
  55166. * Maximum power of emitting particles.
  55167. */
  55168. this.maxEmitPower = 1;
  55169. /**
  55170. * Minimum life time of emitting particles.
  55171. */
  55172. this.minLifeTime = 1;
  55173. /**
  55174. * Maximum life time of emitting particles.
  55175. */
  55176. this.maxLifeTime = 1;
  55177. /**
  55178. * Minimum Size of emitting particles.
  55179. */
  55180. this.minSize = 1;
  55181. /**
  55182. * Maximum Size of emitting particles.
  55183. */
  55184. this.maxSize = 1;
  55185. /**
  55186. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55187. */
  55188. this.minAngularSpeed = 0;
  55189. /**
  55190. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55191. */
  55192. this.maxAngularSpeed = 0;
  55193. /**
  55194. * The layer mask we are rendering the particles through.
  55195. */
  55196. this.layerMask = 0x0FFFFFFF;
  55197. /**
  55198. * This can help using your own shader to render the particle system.
  55199. * The according effect will be created
  55200. */
  55201. this.customShader = null;
  55202. /**
  55203. * By default particle system starts as soon as they are created. This prevents the
  55204. * automatic start to happen and let you decide when to start emitting particles.
  55205. */
  55206. this.preventAutoStart = false;
  55207. /**
  55208. * Callback triggered when the particle animation is ending.
  55209. */
  55210. this.onAnimationEnd = null;
  55211. /**
  55212. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55213. */
  55214. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55215. /**
  55216. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55217. * to override the particles.
  55218. */
  55219. this.forceDepthWrite = false;
  55220. /**
  55221. * You can use gravity if you want to give an orientation to your particles.
  55222. */
  55223. this.gravity = BABYLON.Vector3.Zero();
  55224. /**
  55225. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55226. */
  55227. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55228. /**
  55229. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55230. */
  55231. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55232. /**
  55233. * Color the particle will have at the end of its lifetime.
  55234. */
  55235. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55236. /**
  55237. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55238. */
  55239. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55240. /**
  55241. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55242. */
  55243. this.spriteCellLoop = true;
  55244. /**
  55245. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55246. */
  55247. this.spriteCellChangeSpeed = 0;
  55248. /**
  55249. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55250. */
  55251. this.startSpriteCellID = 0;
  55252. /**
  55253. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55254. */
  55255. this.endSpriteCellID = 0;
  55256. /**
  55257. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55258. */
  55259. this.spriteCellWidth = 0;
  55260. /**
  55261. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55262. */
  55263. this.spriteCellHeight = 0;
  55264. /**
  55265. * An event triggered when the system is disposed.
  55266. */
  55267. this.onDisposeObservable = new BABYLON.Observable();
  55268. this._particles = new Array();
  55269. this._stockParticles = new Array();
  55270. this._newPartsExcess = 0;
  55271. this._vertexBuffers = {};
  55272. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55273. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55274. this._scaledDirection = BABYLON.Vector3.Zero();
  55275. this._scaledGravity = BABYLON.Vector3.Zero();
  55276. this._currentRenderId = -1;
  55277. this._started = false;
  55278. this._stopped = false;
  55279. this._actualFrame = 0;
  55280. this._vertexBufferSize = 11;
  55281. // start of sub system methods
  55282. /**
  55283. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55284. * Its lifetime will start back at 0.
  55285. */
  55286. this.recycleParticle = function (particle) {
  55287. var lastParticle = _this._particles.pop();
  55288. if (lastParticle !== particle) {
  55289. lastParticle.copyTo(particle);
  55290. }
  55291. _this._stockParticles.push(lastParticle);
  55292. };
  55293. this._createParticle = function () {
  55294. var particle;
  55295. if (_this._stockParticles.length !== 0) {
  55296. particle = _this._stockParticles.pop();
  55297. particle.age = 0;
  55298. particle.cellIndex = _this.startSpriteCellID;
  55299. }
  55300. else {
  55301. particle = new BABYLON.Particle(_this);
  55302. }
  55303. return particle;
  55304. };
  55305. this._emitFromParticle = function (particle) {
  55306. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55307. return;
  55308. }
  55309. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55310. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55311. subSystem._rootParticleSystem = _this;
  55312. _this.activeSubSystems.push(subSystem);
  55313. subSystem.start();
  55314. };
  55315. this._appendParticleVertexes = null;
  55316. this.id = name;
  55317. this.name = name;
  55318. this._capacity = capacity;
  55319. this._epsilon = epsilon;
  55320. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55321. if (isAnimationSheetEnabled) {
  55322. this._vertexBufferSize = 12;
  55323. }
  55324. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55325. this._customEffect = customEffect;
  55326. scene.particleSystems.push(this);
  55327. this._createIndexBuffer();
  55328. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55329. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55330. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55331. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55332. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55333. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55334. if (this._isAnimationSheetEnabled) {
  55335. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55336. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55337. }
  55338. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55339. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55340. this._vertexBuffers["options"] = options;
  55341. // Default emitter type
  55342. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55343. this.updateFunction = function (particles) {
  55344. for (var index = 0; index < particles.length; index++) {
  55345. var particle = particles[index];
  55346. particle.age += _this._scaledUpdateSpeed;
  55347. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55348. _this._emitFromParticle(particle);
  55349. _this.recycleParticle(particle);
  55350. index--;
  55351. continue;
  55352. }
  55353. else {
  55354. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55355. particle.color.addInPlace(_this._scaledColorStep);
  55356. if (particle.color.a < 0)
  55357. particle.color.a = 0;
  55358. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55359. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55360. particle.position.addInPlace(_this._scaledDirection);
  55361. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55362. particle.direction.addInPlace(_this._scaledGravity);
  55363. if (_this._isAnimationSheetEnabled) {
  55364. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55365. }
  55366. }
  55367. }
  55368. };
  55369. }
  55370. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55371. /**
  55372. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55373. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55374. */
  55375. get: function () {
  55376. if (this.particleEmitterType.direction1) {
  55377. return this.particleEmitterType.direction1;
  55378. }
  55379. return BABYLON.Vector3.Zero();
  55380. },
  55381. set: function (value) {
  55382. if (this.particleEmitterType.direction1) {
  55383. this.particleEmitterType.direction1 = value;
  55384. }
  55385. },
  55386. enumerable: true,
  55387. configurable: true
  55388. });
  55389. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55390. /**
  55391. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55392. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55393. */
  55394. get: function () {
  55395. if (this.particleEmitterType.direction2) {
  55396. return this.particleEmitterType.direction2;
  55397. }
  55398. return BABYLON.Vector3.Zero();
  55399. },
  55400. set: function (value) {
  55401. if (this.particleEmitterType.direction2) {
  55402. this.particleEmitterType.direction2 = value;
  55403. }
  55404. },
  55405. enumerable: true,
  55406. configurable: true
  55407. });
  55408. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55409. /**
  55410. * 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.
  55411. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55412. */
  55413. get: function () {
  55414. if (this.particleEmitterType.minEmitBox) {
  55415. return this.particleEmitterType.minEmitBox;
  55416. }
  55417. return BABYLON.Vector3.Zero();
  55418. },
  55419. set: function (value) {
  55420. if (this.particleEmitterType.minEmitBox) {
  55421. this.particleEmitterType.minEmitBox = value;
  55422. }
  55423. },
  55424. enumerable: true,
  55425. configurable: true
  55426. });
  55427. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55428. /**
  55429. * 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.
  55430. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55431. */
  55432. get: function () {
  55433. if (this.particleEmitterType.maxEmitBox) {
  55434. return this.particleEmitterType.maxEmitBox;
  55435. }
  55436. return BABYLON.Vector3.Zero();
  55437. },
  55438. set: function (value) {
  55439. if (this.particleEmitterType.maxEmitBox) {
  55440. this.particleEmitterType.maxEmitBox = value;
  55441. }
  55442. },
  55443. enumerable: true,
  55444. configurable: true
  55445. });
  55446. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55447. /**
  55448. * Sets a callback that will be triggered when the system is disposed.
  55449. */
  55450. set: function (callback) {
  55451. if (this._onDisposeObserver) {
  55452. this.onDisposeObservable.remove(this._onDisposeObserver);
  55453. }
  55454. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55455. },
  55456. enumerable: true,
  55457. configurable: true
  55458. });
  55459. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55460. /**
  55461. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55462. */
  55463. get: function () {
  55464. return this._isAnimationSheetEnabled;
  55465. },
  55466. enumerable: true,
  55467. configurable: true
  55468. });
  55469. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55470. //end of Sub-emitter
  55471. /**
  55472. * Gets the current list of active particles
  55473. */
  55474. get: function () {
  55475. return this._particles;
  55476. },
  55477. enumerable: true,
  55478. configurable: true
  55479. });
  55480. /**
  55481. * Returns the string "ParticleSystem"
  55482. * @returns a string containing the class name
  55483. */
  55484. ParticleSystem.prototype.getClassName = function () {
  55485. return "ParticleSystem";
  55486. };
  55487. ParticleSystem.prototype._createIndexBuffer = function () {
  55488. var indices = [];
  55489. var index = 0;
  55490. for (var count = 0; count < this._capacity; count++) {
  55491. indices.push(index);
  55492. indices.push(index + 1);
  55493. indices.push(index + 2);
  55494. indices.push(index);
  55495. indices.push(index + 2);
  55496. indices.push(index + 3);
  55497. index += 4;
  55498. }
  55499. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55500. };
  55501. /**
  55502. * Gets the maximum number of particles active at the same time.
  55503. * @returns The max number of active particles.
  55504. */
  55505. ParticleSystem.prototype.getCapacity = function () {
  55506. return this._capacity;
  55507. };
  55508. /**
  55509. * Gets Wether there are still active particles in the system.
  55510. * @returns True if it is alive, otherwise false.
  55511. */
  55512. ParticleSystem.prototype.isAlive = function () {
  55513. return this._alive;
  55514. };
  55515. /**
  55516. * Gets Wether the system has been started.
  55517. * @returns True if it has been started, otherwise false.
  55518. */
  55519. ParticleSystem.prototype.isStarted = function () {
  55520. return this._started;
  55521. };
  55522. /**
  55523. * Starts the particle system and begins to emit.
  55524. */
  55525. ParticleSystem.prototype.start = function () {
  55526. this._started = true;
  55527. this._stopped = false;
  55528. this._actualFrame = 0;
  55529. if (this.subEmitters && this.subEmitters.length != 0) {
  55530. this.activeSubSystems = new Array();
  55531. }
  55532. };
  55533. /**
  55534. * Stops the particle system.
  55535. * @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.
  55536. */
  55537. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55538. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55539. this._stopped = true;
  55540. if (stopSubEmitters) {
  55541. this._stopSubEmitters();
  55542. }
  55543. };
  55544. // animation sheet
  55545. /**
  55546. * Remove all active particles
  55547. */
  55548. ParticleSystem.prototype.reset = function () {
  55549. this._stockParticles = [];
  55550. this._particles = [];
  55551. };
  55552. /**
  55553. * @ignore (for internal use only)
  55554. */
  55555. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55556. var offset = index * this._vertexBufferSize;
  55557. this._vertexData[offset] = particle.position.x;
  55558. this._vertexData[offset + 1] = particle.position.y;
  55559. this._vertexData[offset + 2] = particle.position.z;
  55560. this._vertexData[offset + 3] = particle.color.r;
  55561. this._vertexData[offset + 4] = particle.color.g;
  55562. this._vertexData[offset + 5] = particle.color.b;
  55563. this._vertexData[offset + 6] = particle.color.a;
  55564. this._vertexData[offset + 7] = particle.angle;
  55565. this._vertexData[offset + 8] = particle.size;
  55566. this._vertexData[offset + 9] = offsetX;
  55567. this._vertexData[offset + 10] = offsetY;
  55568. };
  55569. /**
  55570. * @ignore (for internal use only)
  55571. */
  55572. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55573. if (offsetX === 0)
  55574. offsetX = this._epsilon;
  55575. else if (offsetX === 1)
  55576. offsetX = 1 - this._epsilon;
  55577. if (offsetY === 0)
  55578. offsetY = this._epsilon;
  55579. else if (offsetY === 1)
  55580. offsetY = 1 - this._epsilon;
  55581. var offset = index * this._vertexBufferSize;
  55582. this._vertexData[offset] = particle.position.x;
  55583. this._vertexData[offset + 1] = particle.position.y;
  55584. this._vertexData[offset + 2] = particle.position.z;
  55585. this._vertexData[offset + 3] = particle.color.r;
  55586. this._vertexData[offset + 4] = particle.color.g;
  55587. this._vertexData[offset + 5] = particle.color.b;
  55588. this._vertexData[offset + 6] = particle.color.a;
  55589. this._vertexData[offset + 7] = particle.angle;
  55590. this._vertexData[offset + 8] = particle.size;
  55591. this._vertexData[offset + 9] = offsetX;
  55592. this._vertexData[offset + 10] = offsetY;
  55593. this._vertexData[offset + 11] = particle.cellIndex;
  55594. };
  55595. ParticleSystem.prototype._stopSubEmitters = function () {
  55596. if (!this.activeSubSystems) {
  55597. return;
  55598. }
  55599. this.activeSubSystems.forEach(function (subSystem) {
  55600. subSystem.stop(true);
  55601. });
  55602. this.activeSubSystems = new Array();
  55603. };
  55604. ParticleSystem.prototype._removeFromRoot = function () {
  55605. if (!this._rootParticleSystem) {
  55606. return;
  55607. }
  55608. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55609. if (index !== -1) {
  55610. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55611. }
  55612. };
  55613. // end of sub system methods
  55614. ParticleSystem.prototype._update = function (newParticles) {
  55615. // Update current
  55616. this._alive = this._particles.length > 0;
  55617. this.updateFunction(this._particles);
  55618. // Add new ones
  55619. var worldMatrix;
  55620. if (this.emitter.position) {
  55621. var emitterMesh = this.emitter;
  55622. worldMatrix = emitterMesh.getWorldMatrix();
  55623. }
  55624. else {
  55625. var emitterPosition = this.emitter;
  55626. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55627. }
  55628. var particle;
  55629. for (var index = 0; index < newParticles; index++) {
  55630. if (this._particles.length === this._capacity) {
  55631. break;
  55632. }
  55633. particle = this._createParticle();
  55634. this._particles.push(particle);
  55635. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55636. if (this.startPositionFunction) {
  55637. this.startPositionFunction(worldMatrix, particle.position, particle);
  55638. }
  55639. else {
  55640. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55641. }
  55642. if (this.startDirectionFunction) {
  55643. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55644. }
  55645. else {
  55646. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55647. }
  55648. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55649. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55650. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55651. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55652. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55653. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55654. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55655. }
  55656. };
  55657. ParticleSystem.prototype._getEffect = function () {
  55658. if (this._customEffect) {
  55659. return this._customEffect;
  55660. }
  55661. ;
  55662. var defines = [];
  55663. if (this._scene.clipPlane) {
  55664. defines.push("#define CLIPPLANE");
  55665. }
  55666. if (this._isAnimationSheetEnabled) {
  55667. defines.push("#define ANIMATESHEET");
  55668. }
  55669. // Effect
  55670. var join = defines.join("\n");
  55671. if (this._cachedDefines !== join) {
  55672. this._cachedDefines = join;
  55673. var attributesNamesOrOptions;
  55674. var effectCreationOption;
  55675. if (this._isAnimationSheetEnabled) {
  55676. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55677. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55678. }
  55679. else {
  55680. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55681. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55682. }
  55683. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55684. }
  55685. return this._effect;
  55686. };
  55687. /**
  55688. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55689. */
  55690. ParticleSystem.prototype.animate = function () {
  55691. if (!this._started)
  55692. return;
  55693. var effect = this._getEffect();
  55694. // Check
  55695. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55696. return;
  55697. if (this._currentRenderId === this._scene.getRenderId()) {
  55698. return;
  55699. }
  55700. this._currentRenderId = this._scene.getRenderId();
  55701. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55702. // determine the number of particles we need to create
  55703. var newParticles;
  55704. if (this.manualEmitCount > -1) {
  55705. newParticles = this.manualEmitCount;
  55706. this._newPartsExcess = 0;
  55707. this.manualEmitCount = 0;
  55708. }
  55709. else {
  55710. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55711. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55712. }
  55713. if (this._newPartsExcess > 1.0) {
  55714. newParticles += this._newPartsExcess >> 0;
  55715. this._newPartsExcess -= this._newPartsExcess >> 0;
  55716. }
  55717. this._alive = false;
  55718. if (!this._stopped) {
  55719. this._actualFrame += this._scaledUpdateSpeed;
  55720. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55721. this.stop();
  55722. }
  55723. else {
  55724. newParticles = 0;
  55725. }
  55726. this._update(newParticles);
  55727. // Stopped?
  55728. if (this._stopped) {
  55729. if (!this._alive) {
  55730. this._started = false;
  55731. if (this.onAnimationEnd) {
  55732. this.onAnimationEnd();
  55733. }
  55734. if (this.disposeOnStop) {
  55735. this._scene._toBeDisposed.push(this);
  55736. }
  55737. }
  55738. }
  55739. // Animation sheet
  55740. if (this._isAnimationSheetEnabled) {
  55741. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55742. }
  55743. else {
  55744. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55745. }
  55746. // Update VBO
  55747. var offset = 0;
  55748. for (var index = 0; index < this._particles.length; index++) {
  55749. var particle = this._particles[index];
  55750. this._appendParticleVertexes(offset, particle);
  55751. offset += 4;
  55752. }
  55753. if (this._vertexBuffer) {
  55754. this._vertexBuffer.update(this._vertexData);
  55755. }
  55756. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55757. this.stop();
  55758. }
  55759. };
  55760. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55761. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55762. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55763. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55764. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55765. };
  55766. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55767. this._appendParticleVertex(offset++, particle, 0, 0);
  55768. this._appendParticleVertex(offset++, particle, 1, 0);
  55769. this._appendParticleVertex(offset++, particle, 1, 1);
  55770. this._appendParticleVertex(offset++, particle, 0, 1);
  55771. };
  55772. /**
  55773. * Rebuilds the particle system.
  55774. */
  55775. ParticleSystem.prototype.rebuild = function () {
  55776. this._createIndexBuffer();
  55777. if (this._vertexBuffer) {
  55778. this._vertexBuffer._rebuild();
  55779. }
  55780. };
  55781. /**
  55782. * Is this system ready to be used/rendered
  55783. * @return true if the system is ready
  55784. */
  55785. ParticleSystem.prototype.isReady = function () {
  55786. var effect = this._getEffect();
  55787. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55788. return false;
  55789. }
  55790. return true;
  55791. };
  55792. /**
  55793. * Renders the particle system in its current state.
  55794. * @returns the current number of particles
  55795. */
  55796. ParticleSystem.prototype.render = function () {
  55797. var effect = this._getEffect();
  55798. // Check
  55799. if (!this.isReady() || !this._particles.length) {
  55800. return 0;
  55801. }
  55802. var engine = this._scene.getEngine();
  55803. // Render
  55804. engine.enableEffect(effect);
  55805. engine.setState(false);
  55806. var viewMatrix = this._scene.getViewMatrix();
  55807. effect.setTexture("diffuseSampler", this.particleTexture);
  55808. effect.setMatrix("view", viewMatrix);
  55809. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55810. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55811. var baseSize = this.particleTexture.getBaseSize();
  55812. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55813. }
  55814. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55815. if (this._scene.clipPlane) {
  55816. var clipPlane = this._scene.clipPlane;
  55817. var invView = viewMatrix.clone();
  55818. invView.invert();
  55819. effect.setMatrix("invView", invView);
  55820. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55821. }
  55822. // VBOs
  55823. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55824. // Draw order
  55825. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55826. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55827. }
  55828. else {
  55829. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55830. }
  55831. if (this.forceDepthWrite) {
  55832. engine.setDepthWrite(true);
  55833. }
  55834. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55835. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55836. return this._particles.length;
  55837. };
  55838. /**
  55839. * Disposes the particle system and free the associated resources
  55840. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55841. */
  55842. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55843. if (disposeTexture === void 0) { disposeTexture = true; }
  55844. if (this._vertexBuffer) {
  55845. this._vertexBuffer.dispose();
  55846. this._vertexBuffer = null;
  55847. }
  55848. if (this._indexBuffer) {
  55849. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55850. this._indexBuffer = null;
  55851. }
  55852. if (disposeTexture && this.particleTexture) {
  55853. this.particleTexture.dispose();
  55854. this.particleTexture = null;
  55855. }
  55856. this._removeFromRoot();
  55857. // Remove from scene
  55858. var index = this._scene.particleSystems.indexOf(this);
  55859. if (index > -1) {
  55860. this._scene.particleSystems.splice(index, 1);
  55861. }
  55862. // Callback
  55863. this.onDisposeObservable.notifyObservers(this);
  55864. this.onDisposeObservable.clear();
  55865. };
  55866. /**
  55867. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55868. * @param radius The radius of the sphere to emit from
  55869. * @returns the emitter
  55870. */
  55871. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55872. if (radius === void 0) { radius = 1; }
  55873. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55874. this.particleEmitterType = particleEmitter;
  55875. return particleEmitter;
  55876. };
  55877. /**
  55878. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55879. * @param radius The radius of the sphere to emit from
  55880. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55881. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55882. * @returns the emitter
  55883. */
  55884. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55885. if (radius === void 0) { radius = 1; }
  55886. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55887. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55888. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55889. this.particleEmitterType = particleEmitter;
  55890. return particleEmitter;
  55891. };
  55892. /**
  55893. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55894. * @param radius The radius of the cone to emit from
  55895. * @param angle The base angle of the cone
  55896. * @returns the emitter
  55897. */
  55898. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55899. if (radius === void 0) { radius = 1; }
  55900. if (angle === void 0) { angle = Math.PI / 4; }
  55901. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55902. this.particleEmitterType = particleEmitter;
  55903. return particleEmitter;
  55904. };
  55905. // 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.
  55906. /**
  55907. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55908. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55909. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55910. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55911. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55912. * @returns the emitter
  55913. */
  55914. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55915. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55916. this.particleEmitterType = particleEmitter;
  55917. this.direction1 = direction1;
  55918. this.direction2 = direction2;
  55919. this.minEmitBox = minEmitBox;
  55920. this.maxEmitBox = maxEmitBox;
  55921. return particleEmitter;
  55922. };
  55923. // Clone
  55924. /**
  55925. * Clones the particle system.
  55926. * @param name The name of the cloned object
  55927. * @param newEmitter The new emitter to use
  55928. * @returns the cloned particle system
  55929. */
  55930. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55931. var custom = null;
  55932. var program = null;
  55933. if (this.customShader != null) {
  55934. program = this.customShader;
  55935. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55936. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55937. }
  55938. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55939. result.customShader = program;
  55940. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55941. if (newEmitter === undefined) {
  55942. newEmitter = this.emitter;
  55943. }
  55944. result.emitter = newEmitter;
  55945. if (this.particleTexture) {
  55946. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55947. }
  55948. if (!this.preventAutoStart) {
  55949. result.start();
  55950. }
  55951. return result;
  55952. };
  55953. /**
  55954. * Serializes the particle system to a JSON object.
  55955. * @returns the JSON object
  55956. */
  55957. ParticleSystem.prototype.serialize = function () {
  55958. var serializationObject = {};
  55959. serializationObject.name = this.name;
  55960. serializationObject.id = this.id;
  55961. // Emitter
  55962. if (this.emitter.position) {
  55963. var emitterMesh = this.emitter;
  55964. serializationObject.emitterId = emitterMesh.id;
  55965. }
  55966. else {
  55967. var emitterPosition = this.emitter;
  55968. serializationObject.emitter = emitterPosition.asArray();
  55969. }
  55970. serializationObject.capacity = this.getCapacity();
  55971. if (this.particleTexture) {
  55972. serializationObject.textureName = this.particleTexture.name;
  55973. }
  55974. // Animations
  55975. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  55976. // Particle system
  55977. serializationObject.minAngularSpeed = this.minAngularSpeed;
  55978. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  55979. serializationObject.minSize = this.minSize;
  55980. serializationObject.maxSize = this.maxSize;
  55981. serializationObject.minEmitPower = this.minEmitPower;
  55982. serializationObject.maxEmitPower = this.maxEmitPower;
  55983. serializationObject.minLifeTime = this.minLifeTime;
  55984. serializationObject.maxLifeTime = this.maxLifeTime;
  55985. serializationObject.emitRate = this.emitRate;
  55986. serializationObject.minEmitBox = this.minEmitBox.asArray();
  55987. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  55988. serializationObject.gravity = this.gravity.asArray();
  55989. serializationObject.direction1 = this.direction1.asArray();
  55990. serializationObject.direction2 = this.direction2.asArray();
  55991. serializationObject.color1 = this.color1.asArray();
  55992. serializationObject.color2 = this.color2.asArray();
  55993. serializationObject.colorDead = this.colorDead.asArray();
  55994. serializationObject.updateSpeed = this.updateSpeed;
  55995. serializationObject.targetStopDuration = this.targetStopDuration;
  55996. serializationObject.textureMask = this.textureMask.asArray();
  55997. serializationObject.blendMode = this.blendMode;
  55998. serializationObject.customShader = this.customShader;
  55999. serializationObject.preventAutoStart = this.preventAutoStart;
  56000. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56001. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56002. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56003. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56004. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56005. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56006. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56007. // Emitter
  56008. if (this.particleEmitterType) {
  56009. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56010. }
  56011. return serializationObject;
  56012. };
  56013. /**
  56014. * Parses a JSON object to create a particle system.
  56015. * @param parsedParticleSystem The JSON object to parse
  56016. * @param scene The scene to create the particle system in
  56017. * @param rootUrl The root url to use to load external dependencies like texture
  56018. * @returns the Parsed particle system
  56019. */
  56020. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56021. var name = parsedParticleSystem.name;
  56022. var custom = null;
  56023. var program = null;
  56024. if (parsedParticleSystem.customShader) {
  56025. program = parsedParticleSystem.customShader;
  56026. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56027. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56028. }
  56029. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56030. particleSystem.customShader = program;
  56031. if (parsedParticleSystem.id) {
  56032. particleSystem.id = parsedParticleSystem.id;
  56033. }
  56034. // Auto start
  56035. if (parsedParticleSystem.preventAutoStart) {
  56036. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56037. }
  56038. // Texture
  56039. if (parsedParticleSystem.textureName) {
  56040. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56041. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56042. }
  56043. // Emitter
  56044. if (parsedParticleSystem.emitterId) {
  56045. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56046. }
  56047. else {
  56048. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56049. }
  56050. // Animations
  56051. if (parsedParticleSystem.animations) {
  56052. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56053. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56054. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56055. }
  56056. }
  56057. if (parsedParticleSystem.autoAnimate) {
  56058. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56059. }
  56060. // Particle system
  56061. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56062. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56063. particleSystem.minSize = parsedParticleSystem.minSize;
  56064. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56065. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56066. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56067. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56068. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56069. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56070. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56071. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56072. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56073. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56074. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56075. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56076. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56077. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56078. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56079. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56080. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56081. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56082. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56083. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56084. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56085. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56086. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56087. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56088. if (!particleSystem.preventAutoStart) {
  56089. particleSystem.start();
  56090. }
  56091. return particleSystem;
  56092. };
  56093. /**
  56094. * Source color is added to the destination color without alpha affecting the result.
  56095. */
  56096. ParticleSystem.BLENDMODE_ONEONE = 0;
  56097. /**
  56098. * Blend current color and particle color using particle’s alpha.
  56099. */
  56100. ParticleSystem.BLENDMODE_STANDARD = 1;
  56101. return ParticleSystem;
  56102. }());
  56103. BABYLON.ParticleSystem = ParticleSystem;
  56104. })(BABYLON || (BABYLON = {}));
  56105. //# sourceMappingURL=babylon.particleSystem.js.map
  56106. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56107. var BABYLON;
  56108. (function (BABYLON) {
  56109. /**
  56110. * Particle emitter emitting particles from the inside of a box.
  56111. * It emits the particles randomly between 2 given directions.
  56112. */
  56113. var BoxParticleEmitter = /** @class */ (function () {
  56114. /**
  56115. * Creates a new instance BoxParticleEmitter
  56116. */
  56117. function BoxParticleEmitter() {
  56118. /**
  56119. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56120. */
  56121. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56122. /**
  56123. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56124. */
  56125. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56126. /**
  56127. * 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.
  56128. */
  56129. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56130. /**
  56131. * 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.
  56132. */
  56133. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56134. }
  56135. /**
  56136. * Called by the particle System when the direction is computed for the created particle.
  56137. * @param emitPower is the power of the particle (speed)
  56138. * @param worldMatrix is the world matrix of the particle system
  56139. * @param directionToUpdate is the direction vector to update with the result
  56140. * @param particle is the particle we are computed the direction for
  56141. */
  56142. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56143. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56144. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56145. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56146. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56147. };
  56148. /**
  56149. * Called by the particle System when the position is computed for the created particle.
  56150. * @param worldMatrix is the world matrix of the particle system
  56151. * @param positionToUpdate is the position vector to update with the result
  56152. * @param particle is the particle we are computed the position for
  56153. */
  56154. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56155. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56156. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56157. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56158. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56159. };
  56160. /**
  56161. * Clones the current emitter and returns a copy of it
  56162. * @returns the new emitter
  56163. */
  56164. BoxParticleEmitter.prototype.clone = function () {
  56165. var newOne = new BoxParticleEmitter();
  56166. BABYLON.Tools.DeepCopy(this, newOne);
  56167. return newOne;
  56168. };
  56169. /**
  56170. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56171. * @param effect defines the update shader
  56172. */
  56173. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56174. effect.setVector3("direction1", this.direction1);
  56175. effect.setVector3("direction2", this.direction2);
  56176. effect.setVector3("minEmitBox", this.minEmitBox);
  56177. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56178. };
  56179. /**
  56180. * Returns a string to use to update the GPU particles update shader
  56181. * @returns a string containng the defines string
  56182. */
  56183. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56184. return "#define BOXEMITTER";
  56185. };
  56186. /**
  56187. * Returns the string "BoxEmitter"
  56188. * @returns a string containing the class name
  56189. */
  56190. BoxParticleEmitter.prototype.getClassName = function () {
  56191. return "BoxEmitter";
  56192. };
  56193. /**
  56194. * Serializes the particle system to a JSON object.
  56195. * @returns the JSON object
  56196. */
  56197. BoxParticleEmitter.prototype.serialize = function () {
  56198. var serializationObject = {};
  56199. serializationObject.type = this.getClassName();
  56200. serializationObject.direction1 = this.direction1.asArray();
  56201. ;
  56202. serializationObject.direction2 = this.direction2.asArray();
  56203. ;
  56204. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56205. ;
  56206. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56207. ;
  56208. return serializationObject;
  56209. };
  56210. /**
  56211. * Parse properties from a JSON object
  56212. * @param serializationObject defines the JSON object
  56213. */
  56214. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56215. this.direction1.copyFrom(serializationObject.direction1);
  56216. this.direction2.copyFrom(serializationObject.direction2);
  56217. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56218. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56219. };
  56220. return BoxParticleEmitter;
  56221. }());
  56222. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56223. })(BABYLON || (BABYLON = {}));
  56224. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56225. var BABYLON;
  56226. (function (BABYLON) {
  56227. /**
  56228. * Particle emitter emitting particles from the inside of a cone.
  56229. * It emits the particles alongside the cone volume from the base to the particle.
  56230. * The emission direction might be randomized.
  56231. */
  56232. var ConeParticleEmitter = /** @class */ (function () {
  56233. /**
  56234. * Creates a new instance ConeParticleEmitter
  56235. * @param radius the radius of the emission cone (1 by default)
  56236. * @param angles the cone base angle (PI by default)
  56237. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56238. */
  56239. function ConeParticleEmitter(radius,
  56240. /**
  56241. * The radius of the emission cone.
  56242. */
  56243. angle,
  56244. /**
  56245. * The cone base angle.
  56246. */
  56247. directionRandomizer) {
  56248. if (radius === void 0) { radius = 1; }
  56249. if (angle === void 0) { angle = Math.PI; }
  56250. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56251. this.angle = angle;
  56252. this.directionRandomizer = directionRandomizer;
  56253. this.radius = radius;
  56254. }
  56255. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56256. /**
  56257. * Gets the radius of the emission cone.
  56258. */
  56259. get: function () {
  56260. return this._radius;
  56261. },
  56262. /**
  56263. * Sets the radius of the emission cone.
  56264. */
  56265. set: function (value) {
  56266. this._radius = value;
  56267. if (this.angle !== 0) {
  56268. this._height = value / Math.tan(this.angle / 2);
  56269. }
  56270. else {
  56271. this._height = 1;
  56272. }
  56273. },
  56274. enumerable: true,
  56275. configurable: true
  56276. });
  56277. /**
  56278. * Called by the particle System when the direction is computed for the created particle.
  56279. * @param emitPower is the power of the particle (speed)
  56280. * @param worldMatrix is the world matrix of the particle system
  56281. * @param directionToUpdate is the direction vector to update with the result
  56282. * @param particle is the particle we are computed the direction for
  56283. */
  56284. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56285. if (this.angle === 0) {
  56286. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56287. }
  56288. else {
  56289. // measure the direction Vector from the emitter to the particle.
  56290. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56291. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56292. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56293. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56294. direction.x += randX;
  56295. direction.y += randY;
  56296. direction.z += randZ;
  56297. direction.normalize();
  56298. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56299. }
  56300. };
  56301. /**
  56302. * Called by the particle System when the position is computed for the created particle.
  56303. * @param worldMatrix is the world matrix of the particle system
  56304. * @param positionToUpdate is the position vector to update with the result
  56305. * @param particle is the particle we are computed the position for
  56306. */
  56307. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56308. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56309. var h = BABYLON.Scalar.RandomRange(0, 1);
  56310. // Better distribution in a cone at normal angles.
  56311. h = 1 - h * h;
  56312. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56313. radius = radius * h;
  56314. var randX = radius * Math.sin(s);
  56315. var randZ = radius * Math.cos(s);
  56316. var randY = h * this._height;
  56317. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56318. };
  56319. /**
  56320. * Clones the current emitter and returns a copy of it
  56321. * @returns the new emitter
  56322. */
  56323. ConeParticleEmitter.prototype.clone = function () {
  56324. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56325. BABYLON.Tools.DeepCopy(this, newOne);
  56326. return newOne;
  56327. };
  56328. /**
  56329. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56330. * @param effect defines the update shader
  56331. */
  56332. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56333. effect.setFloat("radius", this.radius);
  56334. effect.setFloat("angle", this.angle);
  56335. effect.setFloat("height", this._height);
  56336. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56337. };
  56338. /**
  56339. * Returns a string to use to update the GPU particles update shader
  56340. * @returns a string containng the defines string
  56341. */
  56342. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56343. return "#define CONEEMITTER";
  56344. };
  56345. /**
  56346. * Returns the string "BoxEmitter"
  56347. * @returns a string containing the class name
  56348. */
  56349. ConeParticleEmitter.prototype.getClassName = function () {
  56350. return "ConeEmitter";
  56351. };
  56352. /**
  56353. * Serializes the particle system to a JSON object.
  56354. * @returns the JSON object
  56355. */
  56356. ConeParticleEmitter.prototype.serialize = function () {
  56357. var serializationObject = {};
  56358. serializationObject.type = this.getClassName();
  56359. serializationObject.radius = this.radius;
  56360. serializationObject.angle = this.angle;
  56361. serializationObject.directionRandomizer = this.directionRandomizer;
  56362. return serializationObject;
  56363. };
  56364. /**
  56365. * Parse properties from a JSON object
  56366. * @param serializationObject defines the JSON object
  56367. */
  56368. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56369. this.radius = serializationObject.radius;
  56370. this.angle = serializationObject.angle;
  56371. this.directionRandomizer = serializationObject.directionRandomizer;
  56372. };
  56373. return ConeParticleEmitter;
  56374. }());
  56375. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56376. })(BABYLON || (BABYLON = {}));
  56377. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56378. var BABYLON;
  56379. (function (BABYLON) {
  56380. /**
  56381. * Particle emitter emitting particles from the inside of a sphere.
  56382. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56383. */
  56384. var SphereParticleEmitter = /** @class */ (function () {
  56385. /**
  56386. * Creates a new instance SphereParticleEmitter
  56387. * @param radius the radius of the emission sphere (1 by default)
  56388. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56389. */
  56390. function SphereParticleEmitter(
  56391. /**
  56392. * The radius of the emission sphere.
  56393. */
  56394. radius,
  56395. /**
  56396. * How much to randomize the particle direction [0-1].
  56397. */
  56398. directionRandomizer) {
  56399. if (radius === void 0) { radius = 1; }
  56400. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56401. this.radius = radius;
  56402. this.directionRandomizer = directionRandomizer;
  56403. }
  56404. /**
  56405. * Called by the particle System when the direction is computed for the created particle.
  56406. * @param emitPower is the power of the particle (speed)
  56407. * @param worldMatrix is the world matrix of the particle system
  56408. * @param directionToUpdate is the direction vector to update with the result
  56409. * @param particle is the particle we are computed the direction for
  56410. */
  56411. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56412. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56413. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56414. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56415. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56416. direction.x += randX;
  56417. direction.y += randY;
  56418. direction.z += randZ;
  56419. direction.normalize();
  56420. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56421. };
  56422. /**
  56423. * Called by the particle System when the position is computed for the created particle.
  56424. * @param worldMatrix is the world matrix of the particle system
  56425. * @param positionToUpdate is the position vector to update with the result
  56426. * @param particle is the particle we are computed the position for
  56427. */
  56428. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56429. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56430. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56431. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56432. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56433. var randY = randRadius * Math.cos(theta);
  56434. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56435. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56436. };
  56437. /**
  56438. * Clones the current emitter and returns a copy of it
  56439. * @returns the new emitter
  56440. */
  56441. SphereParticleEmitter.prototype.clone = function () {
  56442. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56443. BABYLON.Tools.DeepCopy(this, newOne);
  56444. return newOne;
  56445. };
  56446. /**
  56447. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56448. * @param effect defines the update shader
  56449. */
  56450. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56451. effect.setFloat("radius", this.radius);
  56452. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56453. };
  56454. /**
  56455. * Returns a string to use to update the GPU particles update shader
  56456. * @returns a string containng the defines string
  56457. */
  56458. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56459. return "#define SPHEREEMITTER";
  56460. };
  56461. /**
  56462. * Returns the string "SphereParticleEmitter"
  56463. * @returns a string containing the class name
  56464. */
  56465. SphereParticleEmitter.prototype.getClassName = function () {
  56466. return "SphereParticleEmitter";
  56467. };
  56468. /**
  56469. * Serializes the particle system to a JSON object.
  56470. * @returns the JSON object
  56471. */
  56472. SphereParticleEmitter.prototype.serialize = function () {
  56473. var serializationObject = {};
  56474. serializationObject.type = this.getClassName();
  56475. serializationObject.radius = this.radius;
  56476. serializationObject.directionRandomizer = this.directionRandomizer;
  56477. return serializationObject;
  56478. };
  56479. /**
  56480. * Parse properties from a JSON object
  56481. * @param serializationObject defines the JSON object
  56482. */
  56483. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56484. this.radius = serializationObject.radius;
  56485. this.directionRandomizer = serializationObject.directionRandomizer;
  56486. };
  56487. return SphereParticleEmitter;
  56488. }());
  56489. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56490. /**
  56491. * Particle emitter emitting particles from the inside of a sphere.
  56492. * It emits the particles randomly between two vectors.
  56493. */
  56494. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56495. __extends(SphereDirectedParticleEmitter, _super);
  56496. /**
  56497. * Creates a new instance SphereDirectedParticleEmitter
  56498. * @param radius the radius of the emission sphere (1 by default)
  56499. * @param direction1 the min limit of the emission direction (up vector by default)
  56500. * @param direction2 the max limit of the emission direction (up vector by default)
  56501. */
  56502. function SphereDirectedParticleEmitter(radius,
  56503. /**
  56504. * The min limit of the emission direction.
  56505. */
  56506. direction1,
  56507. /**
  56508. * The max limit of the emission direction.
  56509. */
  56510. direction2) {
  56511. if (radius === void 0) { radius = 1; }
  56512. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56513. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56514. var _this = _super.call(this, radius) || this;
  56515. _this.direction1 = direction1;
  56516. _this.direction2 = direction2;
  56517. return _this;
  56518. }
  56519. /**
  56520. * Called by the particle System when the direction is computed for the created particle.
  56521. * @param emitPower is the power of the particle (speed)
  56522. * @param worldMatrix is the world matrix of the particle system
  56523. * @param directionToUpdate is the direction vector to update with the result
  56524. * @param particle is the particle we are computed the direction for
  56525. */
  56526. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56527. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56528. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56529. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56530. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56531. };
  56532. /**
  56533. * Clones the current emitter and returns a copy of it
  56534. * @returns the new emitter
  56535. */
  56536. SphereDirectedParticleEmitter.prototype.clone = function () {
  56537. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56538. BABYLON.Tools.DeepCopy(this, newOne);
  56539. return newOne;
  56540. };
  56541. /**
  56542. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56543. * @param effect defines the update shader
  56544. */
  56545. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56546. effect.setFloat("radius", this.radius);
  56547. effect.setVector3("direction1", this.direction1);
  56548. effect.setVector3("direction2", this.direction2);
  56549. };
  56550. /**
  56551. * Returns a string to use to update the GPU particles update shader
  56552. * @returns a string containng the defines string
  56553. */
  56554. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56555. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56556. };
  56557. /**
  56558. * Returns the string "SphereDirectedParticleEmitter"
  56559. * @returns a string containing the class name
  56560. */
  56561. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56562. return "SphereDirectedParticleEmitter";
  56563. };
  56564. /**
  56565. * Serializes the particle system to a JSON object.
  56566. * @returns the JSON object
  56567. */
  56568. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56569. var serializationObject = _super.prototype.serialize.call(this);
  56570. ;
  56571. serializationObject.direction1 = this.direction1.asArray();
  56572. ;
  56573. serializationObject.direction2 = this.direction2.asArray();
  56574. ;
  56575. return serializationObject;
  56576. };
  56577. /**
  56578. * Parse properties from a JSON object
  56579. * @param serializationObject defines the JSON object
  56580. */
  56581. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56582. _super.prototype.parse.call(this, serializationObject);
  56583. this.direction1.copyFrom(serializationObject.direction1);
  56584. this.direction2.copyFrom(serializationObject.direction2);
  56585. };
  56586. return SphereDirectedParticleEmitter;
  56587. }(SphereParticleEmitter));
  56588. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56589. })(BABYLON || (BABYLON = {}));
  56590. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56591. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56592. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56593. s = arguments[i];
  56594. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56595. t[p] = s[p];
  56596. }
  56597. return t;
  56598. };
  56599. var BABYLON;
  56600. (function (BABYLON) {
  56601. /**
  56602. * This represents a GPU particle system in Babylon
  56603. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56604. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56605. */
  56606. var GPUParticleSystem = /** @class */ (function () {
  56607. /**
  56608. * Instantiates a GPU particle system.
  56609. * 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.
  56610. * @param name The name of the particle system
  56611. * @param capacity The max number of particles alive at the same time
  56612. * @param scene The scene the particle system belongs to
  56613. */
  56614. function GPUParticleSystem(name, options, scene) {
  56615. /**
  56616. * The emitter represents the Mesh or position we are attaching the particle system to.
  56617. */
  56618. this.emitter = null;
  56619. /**
  56620. * The rendering group used by the Particle system to chose when to render.
  56621. */
  56622. this.renderingGroupId = 0;
  56623. /**
  56624. * The layer mask we are rendering the particles through.
  56625. */
  56626. this.layerMask = 0x0FFFFFFF;
  56627. this._targetIndex = 0;
  56628. this._currentRenderId = -1;
  56629. this._started = false;
  56630. this._stopped = false;
  56631. this._timeDelta = 0;
  56632. this._attributesStrideSize = 14;
  56633. this._actualFrame = 0;
  56634. /**
  56635. * List of animations used by the particle system.
  56636. */
  56637. this.animations = [];
  56638. /**
  56639. * An event triggered when the system is disposed.
  56640. */
  56641. this.onDisposeObservable = new BABYLON.Observable();
  56642. /**
  56643. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56644. */
  56645. this.updateSpeed = 0.01;
  56646. /**
  56647. * The amount of time the particle system is running (depends of the overall update speed).
  56648. */
  56649. this.targetStopDuration = 0;
  56650. /**
  56651. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56652. */
  56653. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56654. /**
  56655. * Minimum life time of emitting particles.
  56656. */
  56657. this.minLifeTime = 1;
  56658. /**
  56659. * Maximum life time of emitting particles.
  56660. */
  56661. this.maxLifeTime = 1;
  56662. /**
  56663. * Minimum Size of emitting particles.
  56664. */
  56665. this.minSize = 1;
  56666. /**
  56667. * Maximum Size of emitting particles.
  56668. */
  56669. this.maxSize = 1;
  56670. /**
  56671. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56672. */
  56673. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56674. /**
  56675. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56676. */
  56677. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56678. /**
  56679. * Color the particle will have at the end of its lifetime.
  56680. */
  56681. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56682. /**
  56683. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56684. */
  56685. this.emitRate = 100;
  56686. /**
  56687. * You can use gravity if you want to give an orientation to your particles.
  56688. */
  56689. this.gravity = BABYLON.Vector3.Zero();
  56690. /**
  56691. * Minimum power of emitting particles.
  56692. */
  56693. this.minEmitPower = 1;
  56694. /**
  56695. * Maximum power of emitting particles.
  56696. */
  56697. this.maxEmitPower = 1;
  56698. /**
  56699. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56700. * to override the particles.
  56701. */
  56702. this.forceDepthWrite = false;
  56703. this.id = name;
  56704. this.name = name;
  56705. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56706. this._engine = this._scene.getEngine();
  56707. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56708. this._capacity = fullOptions.capacity;
  56709. this._activeCount = fullOptions.capacity;
  56710. this._currentActiveCount = 0;
  56711. this._scene.particleSystems.push(this);
  56712. this._updateEffectOptions = {
  56713. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56714. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56715. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56716. uniformBuffersNames: [],
  56717. samplers: ["randomSampler"],
  56718. defines: "",
  56719. fallbacks: null,
  56720. onCompiled: null,
  56721. onError: null,
  56722. indexParameters: null,
  56723. maxSimultaneousLights: 0,
  56724. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56725. };
  56726. // Random data
  56727. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56728. var d = [];
  56729. for (var i = 0; i < maxTextureSize; ++i) {
  56730. d.push(Math.random());
  56731. d.push(Math.random());
  56732. d.push(Math.random());
  56733. d.push(Math.random());
  56734. }
  56735. 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);
  56736. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56737. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56738. this._randomTextureSize = maxTextureSize;
  56739. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56740. }
  56741. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56742. /**
  56743. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56744. */
  56745. get: function () {
  56746. if (!BABYLON.Engine.LastCreatedEngine) {
  56747. return false;
  56748. }
  56749. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56750. },
  56751. enumerable: true,
  56752. configurable: true
  56753. });
  56754. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56755. /**
  56756. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56757. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56758. */
  56759. get: function () {
  56760. if (this.particleEmitterType.direction1) {
  56761. return this.particleEmitterType.direction1;
  56762. }
  56763. return BABYLON.Vector3.Zero();
  56764. },
  56765. set: function (value) {
  56766. if (this.particleEmitterType.direction1) {
  56767. this.particleEmitterType.direction1 = value;
  56768. }
  56769. },
  56770. enumerable: true,
  56771. configurable: true
  56772. });
  56773. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56774. /**
  56775. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56776. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56777. */
  56778. get: function () {
  56779. if (this.particleEmitterType.direction2) {
  56780. return this.particleEmitterType.direction2;
  56781. }
  56782. return BABYLON.Vector3.Zero();
  56783. },
  56784. set: function (value) {
  56785. if (this.particleEmitterType.direction2) {
  56786. this.particleEmitterType.direction2 = value;
  56787. }
  56788. },
  56789. enumerable: true,
  56790. configurable: true
  56791. });
  56792. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56793. /**
  56794. * 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.
  56795. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56796. */
  56797. get: function () {
  56798. if (this.particleEmitterType.minEmitBox) {
  56799. return this.particleEmitterType.minEmitBox;
  56800. }
  56801. return BABYLON.Vector3.Zero();
  56802. },
  56803. set: function (value) {
  56804. if (this.particleEmitterType.minEmitBox) {
  56805. this.particleEmitterType.minEmitBox = value;
  56806. }
  56807. },
  56808. enumerable: true,
  56809. configurable: true
  56810. });
  56811. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56812. /**
  56813. * 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.
  56814. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56815. */
  56816. get: function () {
  56817. if (this.particleEmitterType.maxEmitBox) {
  56818. return this.particleEmitterType.maxEmitBox;
  56819. }
  56820. return BABYLON.Vector3.Zero();
  56821. },
  56822. set: function (value) {
  56823. if (this.particleEmitterType.maxEmitBox) {
  56824. this.particleEmitterType.maxEmitBox = value;
  56825. }
  56826. },
  56827. enumerable: true,
  56828. configurable: true
  56829. });
  56830. /**
  56831. * Gets the maximum number of particles active at the same time.
  56832. * @returns The max number of active particles.
  56833. */
  56834. GPUParticleSystem.prototype.getCapacity = function () {
  56835. return this._capacity;
  56836. };
  56837. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56838. /**
  56839. * Gets or set the number of active particles
  56840. */
  56841. get: function () {
  56842. return this._activeCount;
  56843. },
  56844. set: function (value) {
  56845. this._activeCount = Math.min(value, this._capacity);
  56846. },
  56847. enumerable: true,
  56848. configurable: true
  56849. });
  56850. /**
  56851. * Is this system ready to be used/rendered
  56852. * @return true if the system is ready
  56853. */
  56854. GPUParticleSystem.prototype.isReady = function () {
  56855. if (!this._updateEffect) {
  56856. this._recreateUpdateEffect();
  56857. this._recreateRenderEffect();
  56858. return false;
  56859. }
  56860. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56861. return false;
  56862. }
  56863. return true;
  56864. };
  56865. /**
  56866. * Gets Wether the system has been started.
  56867. * @returns True if it has been started, otherwise false.
  56868. */
  56869. GPUParticleSystem.prototype.isStarted = function () {
  56870. return this._started;
  56871. };
  56872. /**
  56873. * Starts the particle system and begins to emit.
  56874. */
  56875. GPUParticleSystem.prototype.start = function () {
  56876. this._started = true;
  56877. this._stopped = false;
  56878. };
  56879. /**
  56880. * Stops the particle system.
  56881. */
  56882. GPUParticleSystem.prototype.stop = function () {
  56883. this._stopped = true;
  56884. };
  56885. /**
  56886. * Remove all active particles
  56887. */
  56888. GPUParticleSystem.prototype.reset = function () {
  56889. this._releaseBuffers();
  56890. this._releaseVAOs();
  56891. this._currentActiveCount = 0;
  56892. this._targetIndex = 0;
  56893. };
  56894. /**
  56895. * Returns the string "GPUParticleSystem"
  56896. * @returns a string containing the class name
  56897. */
  56898. GPUParticleSystem.prototype.getClassName = function () {
  56899. return "GPUParticleSystem";
  56900. };
  56901. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56902. var updateVertexBuffers = {};
  56903. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56904. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56905. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56906. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56907. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56908. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56909. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56910. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56911. this._engine.bindArrayBuffer(null);
  56912. return vao;
  56913. };
  56914. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56915. var renderVertexBuffers = {};
  56916. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56917. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56918. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56919. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56920. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56921. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56922. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56923. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56924. this._engine.bindArrayBuffer(null);
  56925. return vao;
  56926. };
  56927. GPUParticleSystem.prototype._initialize = function (force) {
  56928. if (force === void 0) { force = false; }
  56929. if (this._buffer0 && !force) {
  56930. return;
  56931. }
  56932. var engine = this._scene.getEngine();
  56933. var data = new Array();
  56934. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56935. // position
  56936. data.push(0.0);
  56937. data.push(0.0);
  56938. data.push(0.0);
  56939. // Age and life
  56940. data.push(0.0); // create the particle as a dead one to create a new one at start
  56941. data.push(0.0);
  56942. // Seed
  56943. data.push(Math.random());
  56944. // Size
  56945. data.push(0.0);
  56946. // color
  56947. data.push(0.0);
  56948. data.push(0.0);
  56949. data.push(0.0);
  56950. data.push(0.0);
  56951. // direction
  56952. data.push(0.0);
  56953. data.push(0.0);
  56954. data.push(0.0);
  56955. }
  56956. // Sprite data
  56957. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  56958. -0.5, 0.5, 0, 1,
  56959. -0.5, -0.5, 0, 0,
  56960. 0.5, -0.5, 1, 0]);
  56961. // Buffers
  56962. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56963. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  56964. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  56965. // Update VAO
  56966. this._updateVAO = [];
  56967. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  56968. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  56969. // Render VAO
  56970. this._renderVAO = [];
  56971. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  56972. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  56973. // Links
  56974. this._sourceBuffer = this._buffer0;
  56975. this._targetBuffer = this._buffer1;
  56976. };
  56977. /** @ignore */
  56978. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  56979. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  56980. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  56981. return;
  56982. }
  56983. this._updateEffectOptions.defines = defines;
  56984. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  56985. };
  56986. /** @ignore */
  56987. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  56988. var defines = "";
  56989. if (this._scene.clipPlane) {
  56990. defines = "\n#define CLIPPLANE";
  56991. }
  56992. if (this._renderEffect && this._renderEffect.defines === defines) {
  56993. return;
  56994. }
  56995. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  56996. };
  56997. /**
  56998. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56999. */
  57000. GPUParticleSystem.prototype.animate = function () {
  57001. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57002. this._actualFrame += this._timeDelta;
  57003. if (!this._stopped) {
  57004. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57005. this.stop();
  57006. }
  57007. }
  57008. };
  57009. /**
  57010. * Renders the particle system in its current state.
  57011. * @returns the current number of particles
  57012. */
  57013. GPUParticleSystem.prototype.render = function () {
  57014. if (!this._started) {
  57015. return 0;
  57016. }
  57017. this._recreateUpdateEffect();
  57018. this._recreateRenderEffect();
  57019. if (!this.isReady()) {
  57020. return 0;
  57021. }
  57022. if (this._currentRenderId === this._scene.getRenderId()) {
  57023. return 0;
  57024. }
  57025. this._currentRenderId = this._scene.getRenderId();
  57026. // Get everything ready to render
  57027. this._initialize();
  57028. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57029. // Enable update effect
  57030. this._engine.enableEffect(this._updateEffect);
  57031. this._engine.setState(false);
  57032. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57033. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57034. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57035. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57036. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57037. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57038. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57039. this._updateEffect.setDirectColor4("color1", this.color1);
  57040. this._updateEffect.setDirectColor4("color2", this.color2);
  57041. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57042. this._updateEffect.setVector3("gravity", this.gravity);
  57043. if (this.particleEmitterType) {
  57044. this.particleEmitterType.applyToShader(this._updateEffect);
  57045. }
  57046. var emitterWM;
  57047. if (this.emitter.position) {
  57048. var emitterMesh = this.emitter;
  57049. emitterWM = emitterMesh.getWorldMatrix();
  57050. }
  57051. else {
  57052. var emitterPosition = this.emitter;
  57053. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57054. }
  57055. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57056. // Bind source VAO
  57057. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57058. // Update
  57059. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57060. this._engine.setRasterizerState(false);
  57061. this._engine.beginTransformFeedback();
  57062. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57063. this._engine.endTransformFeedback();
  57064. this._engine.setRasterizerState(true);
  57065. this._engine.bindTransformFeedbackBuffer(null);
  57066. // Enable render effect
  57067. this._engine.enableEffect(this._renderEffect);
  57068. var viewMatrix = this._scene.getViewMatrix();
  57069. this._renderEffect.setMatrix("view", viewMatrix);
  57070. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57071. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57072. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57073. if (this._scene.clipPlane) {
  57074. var clipPlane = this._scene.clipPlane;
  57075. var invView = viewMatrix.clone();
  57076. invView.invert();
  57077. this._renderEffect.setMatrix("invView", invView);
  57078. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57079. }
  57080. // Draw order
  57081. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57082. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57083. }
  57084. else {
  57085. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57086. }
  57087. if (this.forceDepthWrite) {
  57088. this._engine.setDepthWrite(true);
  57089. }
  57090. // Bind source VAO
  57091. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57092. // Render
  57093. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57094. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57095. // Switch VAOs
  57096. this._targetIndex++;
  57097. if (this._targetIndex === 2) {
  57098. this._targetIndex = 0;
  57099. }
  57100. // Switch buffers
  57101. var tmpBuffer = this._sourceBuffer;
  57102. this._sourceBuffer = this._targetBuffer;
  57103. this._targetBuffer = tmpBuffer;
  57104. return this._currentActiveCount;
  57105. };
  57106. /**
  57107. * Rebuilds the particle system
  57108. */
  57109. GPUParticleSystem.prototype.rebuild = function () {
  57110. this._initialize(true);
  57111. };
  57112. GPUParticleSystem.prototype._releaseBuffers = function () {
  57113. if (this._buffer0) {
  57114. this._buffer0.dispose();
  57115. this._buffer0 = null;
  57116. }
  57117. if (this._buffer1) {
  57118. this._buffer1.dispose();
  57119. this._buffer1 = null;
  57120. }
  57121. if (this._spriteBuffer) {
  57122. this._spriteBuffer.dispose();
  57123. this._spriteBuffer = null;
  57124. }
  57125. };
  57126. GPUParticleSystem.prototype._releaseVAOs = function () {
  57127. if (!this._updateVAO) {
  57128. return;
  57129. }
  57130. for (var index = 0; index < this._updateVAO.length; index++) {
  57131. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57132. }
  57133. this._updateVAO = [];
  57134. for (var index = 0; index < this._renderVAO.length; index++) {
  57135. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57136. }
  57137. this._renderVAO = [];
  57138. };
  57139. /**
  57140. * Disposes the particle system and free the associated resources
  57141. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57142. */
  57143. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57144. if (disposeTexture === void 0) { disposeTexture = true; }
  57145. var index = this._scene.particleSystems.indexOf(this);
  57146. if (index > -1) {
  57147. this._scene.particleSystems.splice(index, 1);
  57148. }
  57149. this._releaseBuffers();
  57150. this._releaseVAOs();
  57151. if (this._randomTexture) {
  57152. this._randomTexture.dispose();
  57153. this._randomTexture = null;
  57154. }
  57155. if (disposeTexture && this.particleTexture) {
  57156. this.particleTexture.dispose();
  57157. this.particleTexture = null;
  57158. }
  57159. // Callback
  57160. this.onDisposeObservable.notifyObservers(this);
  57161. this.onDisposeObservable.clear();
  57162. };
  57163. /**
  57164. * Clones the particle system.
  57165. * @param name The name of the cloned object
  57166. * @param newEmitter The new emitter to use
  57167. * @returns the cloned particle system
  57168. */
  57169. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57170. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57171. BABYLON.Tools.DeepCopy(this, result);
  57172. if (newEmitter === undefined) {
  57173. newEmitter = this.emitter;
  57174. }
  57175. result.emitter = newEmitter;
  57176. if (this.particleTexture) {
  57177. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57178. }
  57179. return result;
  57180. };
  57181. /**
  57182. * Serializes the particle system to a JSON object.
  57183. * @returns the JSON object
  57184. */
  57185. GPUParticleSystem.prototype.serialize = function () {
  57186. var serializationObject = {};
  57187. serializationObject.name = this.name;
  57188. serializationObject.id = this.id;
  57189. // Emitter
  57190. if (this.emitter.position) {
  57191. var emitterMesh = this.emitter;
  57192. serializationObject.emitterId = emitterMesh.id;
  57193. }
  57194. else {
  57195. var emitterPosition = this.emitter;
  57196. serializationObject.emitter = emitterPosition.asArray();
  57197. }
  57198. serializationObject.capacity = this.getCapacity();
  57199. if (this.particleTexture) {
  57200. serializationObject.textureName = this.particleTexture.name;
  57201. }
  57202. // Animations
  57203. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57204. // Particle system
  57205. serializationObject.activeParticleCount = this.activeParticleCount;
  57206. serializationObject.randomTextureSize = this._randomTextureSize;
  57207. serializationObject.minSize = this.minSize;
  57208. serializationObject.maxSize = this.maxSize;
  57209. serializationObject.minEmitPower = this.minEmitPower;
  57210. serializationObject.maxEmitPower = this.maxEmitPower;
  57211. serializationObject.minLifeTime = this.minLifeTime;
  57212. serializationObject.maxLifeTime = this.maxLifeTime;
  57213. serializationObject.emitRate = this.emitRate;
  57214. serializationObject.gravity = this.gravity.asArray();
  57215. serializationObject.color1 = this.color1.asArray();
  57216. serializationObject.color2 = this.color2.asArray();
  57217. serializationObject.colorDead = this.colorDead.asArray();
  57218. serializationObject.updateSpeed = this.updateSpeed;
  57219. serializationObject.targetStopDuration = this.targetStopDuration;
  57220. serializationObject.blendMode = this.blendMode;
  57221. // Emitter
  57222. if (this.particleEmitterType) {
  57223. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57224. }
  57225. return serializationObject;
  57226. };
  57227. /**
  57228. * Parses a JSON object to create a GPU particle system.
  57229. * @param parsedParticleSystem The JSON object to parse
  57230. * @param scene The scene to create the particle system in
  57231. * @param rootUrl The root url to use to load external dependencies like texture
  57232. * @returns the parsed GPU particle system
  57233. */
  57234. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57235. var name = parsedParticleSystem.name;
  57236. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57237. if (parsedParticleSystem.id) {
  57238. particleSystem.id = parsedParticleSystem.id;
  57239. }
  57240. // Texture
  57241. if (parsedParticleSystem.textureName) {
  57242. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57243. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57244. }
  57245. // Emitter
  57246. if (parsedParticleSystem.emitterId) {
  57247. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57248. }
  57249. else {
  57250. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57251. }
  57252. // Animations
  57253. if (parsedParticleSystem.animations) {
  57254. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57255. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57256. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57257. }
  57258. }
  57259. // Particle system
  57260. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57261. particleSystem.minSize = parsedParticleSystem.minSize;
  57262. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57263. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57264. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57265. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57266. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57267. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57268. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57269. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57270. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57271. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57272. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57273. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57274. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57275. // Emitter
  57276. if (parsedParticleSystem.particleEmitterType) {
  57277. var emitterType = void 0;
  57278. switch (parsedParticleSystem.particleEmitterType.type) {
  57279. case "SphereEmitter":
  57280. emitterType = new BABYLON.SphereParticleEmitter();
  57281. break;
  57282. case "SphereDirectedParticleEmitter":
  57283. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57284. break;
  57285. case "ConeEmitter":
  57286. emitterType = new BABYLON.ConeParticleEmitter();
  57287. break;
  57288. case "BoxEmitter":
  57289. default:
  57290. emitterType = new BABYLON.BoxParticleEmitter();
  57291. break;
  57292. }
  57293. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57294. particleSystem.particleEmitterType = emitterType;
  57295. }
  57296. return particleSystem;
  57297. };
  57298. return GPUParticleSystem;
  57299. }());
  57300. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57301. })(BABYLON || (BABYLON = {}));
  57302. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57303. var BABYLON;
  57304. (function (BABYLON) {
  57305. /**
  57306. * Represents one particle of a solid particle system.
  57307. */
  57308. var SolidParticle = /** @class */ (function () {
  57309. /**
  57310. * Creates a Solid Particle object.
  57311. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57312. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57313. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57314. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57315. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57316. * @param shapeId (integer) is the model shape identifier in the SPS.
  57317. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57318. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57319. */
  57320. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57321. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57322. /**
  57323. * particle global index
  57324. */
  57325. this.idx = 0;
  57326. /**
  57327. * The color of the particle
  57328. */
  57329. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57330. /**
  57331. * The world space position of the particle.
  57332. */
  57333. this.position = BABYLON.Vector3.Zero();
  57334. /**
  57335. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57336. */
  57337. this.rotation = BABYLON.Vector3.Zero();
  57338. /**
  57339. * The scaling of the particle.
  57340. */
  57341. this.scaling = BABYLON.Vector3.One();
  57342. /**
  57343. * The uvs of the particle.
  57344. */
  57345. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57346. /**
  57347. * The current speed of the particle.
  57348. */
  57349. this.velocity = BABYLON.Vector3.Zero();
  57350. /**
  57351. * The pivot point in the particle local space.
  57352. */
  57353. this.pivot = BABYLON.Vector3.Zero();
  57354. /**
  57355. * Must the particle be translated from its pivot point in its local space ?
  57356. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57357. * Default : false
  57358. */
  57359. this.translateFromPivot = false;
  57360. /**
  57361. * Is the particle active or not ?
  57362. */
  57363. this.alive = true;
  57364. /**
  57365. * Is the particle visible or not ?
  57366. */
  57367. this.isVisible = true;
  57368. /**
  57369. * Index of this particle in the global "positions" array (Internal use)
  57370. */
  57371. this._pos = 0;
  57372. /**
  57373. * Index of this particle in the global "indices" array (Internal use)
  57374. */
  57375. this._ind = 0;
  57376. /**
  57377. * ModelShape id of this particle
  57378. */
  57379. this.shapeId = 0;
  57380. /**
  57381. * Index of the particle in its shape id (Internal use)
  57382. */
  57383. this.idxInShape = 0;
  57384. /**
  57385. * Still set as invisible in order to skip useless computations (Internal use)
  57386. */
  57387. this._stillInvisible = false;
  57388. /**
  57389. * Last computed particle rotation matrix
  57390. */
  57391. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57392. /**
  57393. * Parent particle Id, if any.
  57394. * Default null.
  57395. */
  57396. this.parentId = null;
  57397. /**
  57398. * Internal global position in the SPS.
  57399. */
  57400. this._globalPosition = BABYLON.Vector3.Zero();
  57401. this.idx = particleIndex;
  57402. this._pos = positionIndex;
  57403. this._ind = indiceIndex;
  57404. this._model = model;
  57405. this.shapeId = shapeId;
  57406. this.idxInShape = idxInShape;
  57407. this._sps = sps;
  57408. if (modelBoundingInfo) {
  57409. this._modelBoundingInfo = modelBoundingInfo;
  57410. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57411. }
  57412. }
  57413. Object.defineProperty(SolidParticle.prototype, "scale", {
  57414. /**
  57415. * Legacy support, changed scale to scaling
  57416. */
  57417. get: function () {
  57418. return this.scaling;
  57419. },
  57420. /**
  57421. * Legacy support, changed scale to scaling
  57422. */
  57423. set: function (scale) {
  57424. this.scaling = scale;
  57425. },
  57426. enumerable: true,
  57427. configurable: true
  57428. });
  57429. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57430. /**
  57431. * Legacy support, changed quaternion to rotationQuaternion
  57432. */
  57433. get: function () {
  57434. return this.rotationQuaternion;
  57435. },
  57436. /**
  57437. * Legacy support, changed quaternion to rotationQuaternion
  57438. */
  57439. set: function (q) {
  57440. this.rotationQuaternion = q;
  57441. },
  57442. enumerable: true,
  57443. configurable: true
  57444. });
  57445. /**
  57446. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57447. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57448. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57449. * @returns true if it intersects
  57450. */
  57451. SolidParticle.prototype.intersectsMesh = function (target) {
  57452. if (!this._boundingInfo || !target._boundingInfo) {
  57453. return false;
  57454. }
  57455. if (this._sps._bSphereOnly) {
  57456. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57457. }
  57458. return this._boundingInfo.intersects(target._boundingInfo, false);
  57459. };
  57460. return SolidParticle;
  57461. }());
  57462. BABYLON.SolidParticle = SolidParticle;
  57463. /**
  57464. * Represents the shape of the model used by one particle of a solid particle system.
  57465. * SPS internal tool, don't use it manually.
  57466. */
  57467. var ModelShape = /** @class */ (function () {
  57468. /**
  57469. * 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.
  57470. * SPS internal tool, don't use it manually.
  57471. * @ignore
  57472. */
  57473. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57474. /**
  57475. * length of the shape in the model indices array (internal use)
  57476. */
  57477. this._indicesLength = 0;
  57478. this.shapeID = id;
  57479. this._shape = shape;
  57480. this._indicesLength = indicesLength;
  57481. this._shapeUV = shapeUV;
  57482. this._positionFunction = posFunction;
  57483. this._vertexFunction = vtxFunction;
  57484. }
  57485. return ModelShape;
  57486. }());
  57487. BABYLON.ModelShape = ModelShape;
  57488. /**
  57489. * Represents a Depth Sorted Particle in the solid particle system.
  57490. */
  57491. var DepthSortedParticle = /** @class */ (function () {
  57492. function DepthSortedParticle() {
  57493. /**
  57494. * Index of the particle in the "indices" array
  57495. */
  57496. this.ind = 0;
  57497. /**
  57498. * Length of the particle shape in the "indices" array
  57499. */
  57500. this.indicesLength = 0;
  57501. /**
  57502. * Squared distance from the particle to the camera
  57503. */
  57504. this.sqDistance = 0.0;
  57505. }
  57506. return DepthSortedParticle;
  57507. }());
  57508. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57509. })(BABYLON || (BABYLON = {}));
  57510. //# sourceMappingURL=babylon.solidParticle.js.map
  57511. var BABYLON;
  57512. (function (BABYLON) {
  57513. /**
  57514. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57515. *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.
  57516. * The SPS is also a particle system. It provides some methods to manage the particles.
  57517. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57518. *
  57519. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57520. */
  57521. var SolidParticleSystem = /** @class */ (function () {
  57522. /**
  57523. * Creates a SPS (Solid Particle System) object.
  57524. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57525. * @param scene (Scene) is the scene in which the SPS is added.
  57526. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57527. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57528. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57529. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57530. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57531. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57532. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57533. */
  57534. function SolidParticleSystem(name, scene, options) {
  57535. /**
  57536. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57537. * Example : var p = SPS.particles[i];
  57538. */
  57539. this.particles = new Array();
  57540. /**
  57541. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57542. */
  57543. this.nbParticles = 0;
  57544. /**
  57545. * If the particles must ever face the camera (default false). Useful for planar particles.
  57546. */
  57547. this.billboard = false;
  57548. /**
  57549. * Recompute normals when adding a shape
  57550. */
  57551. this.recomputeNormals = true;
  57552. /**
  57553. * This a counter ofr your own usage. It's not set by any SPS functions.
  57554. */
  57555. this.counter = 0;
  57556. /**
  57557. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57558. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57559. */
  57560. this.vars = {};
  57561. /**
  57562. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57563. */
  57564. this._bSphereOnly = false;
  57565. /**
  57566. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57567. */
  57568. this._bSphereRadiusFactor = 1.0;
  57569. this._positions = new Array();
  57570. this._indices = new Array();
  57571. this._normals = new Array();
  57572. this._colors = new Array();
  57573. this._uvs = new Array();
  57574. this._index = 0; // indices index
  57575. this._updatable = true;
  57576. this._pickable = false;
  57577. this._isVisibilityBoxLocked = false;
  57578. this._alwaysVisible = false;
  57579. this._depthSort = false;
  57580. this._shapeCounter = 0;
  57581. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57582. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57583. this._computeParticleColor = true;
  57584. this._computeParticleTexture = true;
  57585. this._computeParticleRotation = true;
  57586. this._computeParticleVertex = false;
  57587. this._computeBoundingBox = false;
  57588. this._depthSortParticles = true;
  57589. this._cam_axisZ = BABYLON.Vector3.Zero();
  57590. this._cam_axisY = BABYLON.Vector3.Zero();
  57591. this._cam_axisX = BABYLON.Vector3.Zero();
  57592. this._axisZ = BABYLON.Axis.Z;
  57593. this._camDir = BABYLON.Vector3.Zero();
  57594. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57595. this._rotMatrix = new BABYLON.Matrix();
  57596. this._invertMatrix = new BABYLON.Matrix();
  57597. this._rotated = BABYLON.Vector3.Zero();
  57598. this._quaternion = new BABYLON.Quaternion();
  57599. this._vertex = BABYLON.Vector3.Zero();
  57600. this._normal = BABYLON.Vector3.Zero();
  57601. this._yaw = 0.0;
  57602. this._pitch = 0.0;
  57603. this._roll = 0.0;
  57604. this._halfroll = 0.0;
  57605. this._halfpitch = 0.0;
  57606. this._halfyaw = 0.0;
  57607. this._sinRoll = 0.0;
  57608. this._cosRoll = 0.0;
  57609. this._sinPitch = 0.0;
  57610. this._cosPitch = 0.0;
  57611. this._sinYaw = 0.0;
  57612. this._cosYaw = 0.0;
  57613. this._mustUnrotateFixedNormals = false;
  57614. this._minimum = BABYLON.Vector3.Zero();
  57615. this._maximum = BABYLON.Vector3.Zero();
  57616. this._minBbox = BABYLON.Vector3.Zero();
  57617. this._maxBbox = BABYLON.Vector3.Zero();
  57618. this._particlesIntersect = false;
  57619. this._depthSortFunction = function (p1, p2) {
  57620. return (p2.sqDistance - p1.sqDistance);
  57621. };
  57622. this._needs32Bits = false;
  57623. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57624. this._scaledPivot = BABYLON.Vector3.Zero();
  57625. this._particleHasParent = false;
  57626. this.name = name;
  57627. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57628. this._camera = scene.activeCamera;
  57629. this._pickable = options ? options.isPickable : false;
  57630. this._depthSort = options ? options.enableDepthSort : false;
  57631. this._particlesIntersect = options ? options.particleIntersection : false;
  57632. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57633. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57634. if (options && options.updatable) {
  57635. this._updatable = options.updatable;
  57636. }
  57637. else {
  57638. this._updatable = true;
  57639. }
  57640. if (this._pickable) {
  57641. this.pickedParticles = [];
  57642. }
  57643. if (this._depthSort) {
  57644. this.depthSortedParticles = [];
  57645. }
  57646. }
  57647. /**
  57648. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57649. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57650. * @returns the created mesh
  57651. */
  57652. SolidParticleSystem.prototype.buildMesh = function () {
  57653. if (this.nbParticles === 0) {
  57654. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57655. this.addShape(triangle, 1);
  57656. triangle.dispose();
  57657. }
  57658. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57659. this._positions32 = new Float32Array(this._positions);
  57660. this._uvs32 = new Float32Array(this._uvs);
  57661. this._colors32 = new Float32Array(this._colors);
  57662. if (this.recomputeNormals) {
  57663. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57664. }
  57665. this._normals32 = new Float32Array(this._normals);
  57666. this._fixedNormal32 = new Float32Array(this._normals);
  57667. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57668. this._unrotateFixedNormals();
  57669. }
  57670. var vertexData = new BABYLON.VertexData();
  57671. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57672. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57673. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57674. if (this._uvs32) {
  57675. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57676. ;
  57677. }
  57678. if (this._colors32) {
  57679. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57680. }
  57681. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57682. vertexData.applyToMesh(mesh, this._updatable);
  57683. this.mesh = mesh;
  57684. this.mesh.isPickable = this._pickable;
  57685. // free memory
  57686. if (!this._depthSort) {
  57687. this._indices = null;
  57688. }
  57689. this._positions = null;
  57690. this._normals = null;
  57691. this._uvs = null;
  57692. this._colors = null;
  57693. if (!this._updatable) {
  57694. this.particles.length = 0;
  57695. }
  57696. return mesh;
  57697. };
  57698. /**
  57699. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57700. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57701. * Thus the particles generated from `digest()` have their property `position` set yet.
  57702. * @param mesh ( Mesh ) is the mesh to be digested
  57703. * @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
  57704. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57705. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57706. * @returns the current SPS
  57707. */
  57708. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57709. var size = (options && options.facetNb) || 1;
  57710. var number = (options && options.number) || 0;
  57711. var delta = (options && options.delta) || 0;
  57712. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57713. var meshInd = mesh.getIndices();
  57714. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57715. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57716. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57717. var f = 0; // facet counter
  57718. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57719. // compute size from number
  57720. if (number) {
  57721. number = (number > totalFacets) ? totalFacets : number;
  57722. size = Math.round(totalFacets / number);
  57723. delta = 0;
  57724. }
  57725. else {
  57726. size = (size > totalFacets) ? totalFacets : size;
  57727. }
  57728. var facetPos = []; // submesh positions
  57729. var facetInd = []; // submesh indices
  57730. var facetUV = []; // submesh UV
  57731. var facetCol = []; // submesh colors
  57732. var barycenter = BABYLON.Vector3.Zero();
  57733. var sizeO = size;
  57734. while (f < totalFacets) {
  57735. size = sizeO + Math.floor((1 + delta) * Math.random());
  57736. if (f > totalFacets - size) {
  57737. size = totalFacets - f;
  57738. }
  57739. // reset temp arrays
  57740. facetPos.length = 0;
  57741. facetInd.length = 0;
  57742. facetUV.length = 0;
  57743. facetCol.length = 0;
  57744. // iterate over "size" facets
  57745. var fi = 0;
  57746. for (var j = f * 3; j < (f + size) * 3; j++) {
  57747. facetInd.push(fi);
  57748. var i = meshInd[j];
  57749. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57750. if (meshUV) {
  57751. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57752. }
  57753. if (meshCol) {
  57754. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57755. }
  57756. fi++;
  57757. }
  57758. // create a model shape for each single particle
  57759. var idx = this.nbParticles;
  57760. var shape = this._posToShape(facetPos);
  57761. var shapeUV = this._uvsToShapeUV(facetUV);
  57762. // compute the barycenter of the shape
  57763. var v;
  57764. for (v = 0; v < shape.length; v++) {
  57765. barycenter.addInPlace(shape[v]);
  57766. }
  57767. barycenter.scaleInPlace(1 / shape.length);
  57768. // shift the shape from its barycenter to the origin
  57769. for (v = 0; v < shape.length; v++) {
  57770. shape[v].subtractInPlace(barycenter);
  57771. }
  57772. var bInfo;
  57773. if (this._particlesIntersect) {
  57774. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57775. }
  57776. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57777. // add the particle in the SPS
  57778. var currentPos = this._positions.length;
  57779. var currentInd = this._indices.length;
  57780. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57781. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57782. // initialize the particle position
  57783. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57784. this._index += shape.length;
  57785. idx++;
  57786. this.nbParticles++;
  57787. this._shapeCounter++;
  57788. f += size;
  57789. }
  57790. return this;
  57791. };
  57792. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57793. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57794. var index = 0;
  57795. var idx = 0;
  57796. for (var p = 0; p < this.particles.length; p++) {
  57797. this._particle = this.particles[p];
  57798. this._shape = this._particle._model._shape;
  57799. if (this._particle.rotationQuaternion) {
  57800. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57801. }
  57802. else {
  57803. this._yaw = this._particle.rotation.y;
  57804. this._pitch = this._particle.rotation.x;
  57805. this._roll = this._particle.rotation.z;
  57806. this._quaternionRotationYPR();
  57807. }
  57808. this._quaternionToRotationMatrix();
  57809. this._rotMatrix.invertToRef(this._invertMatrix);
  57810. for (var pt = 0; pt < this._shape.length; pt++) {
  57811. idx = index + pt * 3;
  57812. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57813. this._fixedNormal32[idx] = this._normal.x;
  57814. this._fixedNormal32[idx + 1] = this._normal.y;
  57815. this._fixedNormal32[idx + 2] = this._normal.z;
  57816. }
  57817. index = idx + 3;
  57818. }
  57819. };
  57820. //reset copy
  57821. SolidParticleSystem.prototype._resetCopy = function () {
  57822. this._copy.position.x = 0;
  57823. this._copy.position.y = 0;
  57824. this._copy.position.z = 0;
  57825. this._copy.rotation.x = 0;
  57826. this._copy.rotation.y = 0;
  57827. this._copy.rotation.z = 0;
  57828. this._copy.rotationQuaternion = null;
  57829. this._copy.scaling.x = 1.0;
  57830. this._copy.scaling.y = 1.0;
  57831. this._copy.scaling.z = 1.0;
  57832. this._copy.uvs.x = 0;
  57833. this._copy.uvs.y = 0;
  57834. this._copy.uvs.z = 1.0;
  57835. this._copy.uvs.w = 1.0;
  57836. this._copy.color = null;
  57837. this._copy.translateFromPivot = false;
  57838. };
  57839. // _meshBuilder : inserts the shape model in the global SPS mesh
  57840. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57841. var i;
  57842. var u = 0;
  57843. var c = 0;
  57844. var n = 0;
  57845. this._resetCopy();
  57846. if (options && options.positionFunction) { // call to custom positionFunction
  57847. options.positionFunction(this._copy, idx, idxInShape);
  57848. this._mustUnrotateFixedNormals = true;
  57849. }
  57850. if (this._copy.rotationQuaternion) {
  57851. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57852. }
  57853. else {
  57854. this._yaw = this._copy.rotation.y;
  57855. this._pitch = this._copy.rotation.x;
  57856. this._roll = this._copy.rotation.z;
  57857. this._quaternionRotationYPR();
  57858. }
  57859. this._quaternionToRotationMatrix();
  57860. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57861. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57862. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57863. if (this._copy.translateFromPivot) {
  57864. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57865. }
  57866. else {
  57867. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57868. }
  57869. for (i = 0; i < shape.length; i++) {
  57870. this._vertex.x = shape[i].x;
  57871. this._vertex.y = shape[i].y;
  57872. this._vertex.z = shape[i].z;
  57873. if (options && options.vertexFunction) {
  57874. options.vertexFunction(this._copy, this._vertex, i);
  57875. }
  57876. this._vertex.x *= this._copy.scaling.x;
  57877. this._vertex.y *= this._copy.scaling.y;
  57878. this._vertex.z *= this._copy.scaling.z;
  57879. this._vertex.x -= this._scaledPivot.x;
  57880. this._vertex.y -= this._scaledPivot.y;
  57881. this._vertex.z -= this._scaledPivot.z;
  57882. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57883. this._rotated.addInPlace(this._pivotBackTranslation);
  57884. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57885. if (meshUV) {
  57886. 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);
  57887. u += 2;
  57888. }
  57889. if (this._copy.color) {
  57890. this._color = this._copy.color;
  57891. }
  57892. else if (meshCol && meshCol[c] !== undefined) {
  57893. this._color.r = meshCol[c];
  57894. this._color.g = meshCol[c + 1];
  57895. this._color.b = meshCol[c + 2];
  57896. this._color.a = meshCol[c + 3];
  57897. }
  57898. else {
  57899. this._color.r = 1.0;
  57900. this._color.g = 1.0;
  57901. this._color.b = 1.0;
  57902. this._color.a = 1.0;
  57903. }
  57904. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57905. c += 4;
  57906. if (!this.recomputeNormals && meshNor) {
  57907. this._normal.x = meshNor[n];
  57908. this._normal.y = meshNor[n + 1];
  57909. this._normal.z = meshNor[n + 2];
  57910. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57911. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57912. n += 3;
  57913. }
  57914. }
  57915. for (i = 0; i < meshInd.length; i++) {
  57916. var current_ind = p + meshInd[i];
  57917. indices.push(current_ind);
  57918. if (current_ind > 65535) {
  57919. this._needs32Bits = true;
  57920. }
  57921. }
  57922. if (this._pickable) {
  57923. var nbfaces = meshInd.length / 3;
  57924. for (i = 0; i < nbfaces; i++) {
  57925. this.pickedParticles.push({ idx: idx, faceId: i });
  57926. }
  57927. }
  57928. if (this._depthSort) {
  57929. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57930. }
  57931. return this._copy;
  57932. };
  57933. // returns a shape array from positions array
  57934. SolidParticleSystem.prototype._posToShape = function (positions) {
  57935. var shape = [];
  57936. for (var i = 0; i < positions.length; i += 3) {
  57937. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57938. }
  57939. return shape;
  57940. };
  57941. // returns a shapeUV array from a Vector4 uvs
  57942. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57943. var shapeUV = [];
  57944. if (uvs) {
  57945. for (var i = 0; i < uvs.length; i++)
  57946. shapeUV.push(uvs[i]);
  57947. }
  57948. return shapeUV;
  57949. };
  57950. // adds a new particle object in the particles array
  57951. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  57952. if (bInfo === void 0) { bInfo = null; }
  57953. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  57954. this.particles.push(sp);
  57955. return sp;
  57956. };
  57957. /**
  57958. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57959. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57960. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  57961. * @param nb (positive integer) the number of particles to be created from this model
  57962. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  57963. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  57964. * @returns the number of shapes in the system
  57965. */
  57966. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57967. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57968. var meshInd = mesh.getIndices();
  57969. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57970. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57971. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57972. var bbInfo;
  57973. if (this._particlesIntersect) {
  57974. bbInfo = mesh.getBoundingInfo();
  57975. }
  57976. var shape = this._posToShape(meshPos);
  57977. var shapeUV = this._uvsToShapeUV(meshUV);
  57978. var posfunc = options ? options.positionFunction : null;
  57979. var vtxfunc = options ? options.vertexFunction : null;
  57980. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  57981. // particles
  57982. var sp;
  57983. var currentCopy;
  57984. var idx = this.nbParticles;
  57985. for (var i = 0; i < nb; i++) {
  57986. var currentPos = this._positions.length;
  57987. var currentInd = this._indices.length;
  57988. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  57989. if (this._updatable) {
  57990. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  57991. sp.position.copyFrom(currentCopy.position);
  57992. sp.rotation.copyFrom(currentCopy.rotation);
  57993. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  57994. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  57995. }
  57996. if (currentCopy.color && sp.color) {
  57997. sp.color.copyFrom(currentCopy.color);
  57998. }
  57999. sp.scaling.copyFrom(currentCopy.scaling);
  58000. sp.uvs.copyFrom(currentCopy.uvs);
  58001. }
  58002. this._index += shape.length;
  58003. idx++;
  58004. }
  58005. this.nbParticles += nb;
  58006. this._shapeCounter++;
  58007. return this._shapeCounter - 1;
  58008. };
  58009. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58010. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58011. this._resetCopy();
  58012. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58013. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58014. }
  58015. if (this._copy.rotationQuaternion) {
  58016. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58017. }
  58018. else {
  58019. this._yaw = this._copy.rotation.y;
  58020. this._pitch = this._copy.rotation.x;
  58021. this._roll = this._copy.rotation.z;
  58022. this._quaternionRotationYPR();
  58023. }
  58024. this._quaternionToRotationMatrix();
  58025. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58026. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58027. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58028. if (this._copy.translateFromPivot) {
  58029. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58030. }
  58031. else {
  58032. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58033. }
  58034. this._shape = particle._model._shape;
  58035. for (var pt = 0; pt < this._shape.length; pt++) {
  58036. this._vertex.x = this._shape[pt].x;
  58037. this._vertex.y = this._shape[pt].y;
  58038. this._vertex.z = this._shape[pt].z;
  58039. if (particle._model._vertexFunction) {
  58040. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58041. }
  58042. this._vertex.x *= this._copy.scaling.x;
  58043. this._vertex.y *= this._copy.scaling.y;
  58044. this._vertex.z *= this._copy.scaling.z;
  58045. this._vertex.x -= this._scaledPivot.x;
  58046. this._vertex.y -= this._scaledPivot.y;
  58047. this._vertex.z -= this._scaledPivot.z;
  58048. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58049. this._rotated.addInPlace(this._pivotBackTranslation);
  58050. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58051. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58052. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58053. }
  58054. particle.position.x = 0.0;
  58055. particle.position.y = 0.0;
  58056. particle.position.z = 0.0;
  58057. particle.rotation.x = 0.0;
  58058. particle.rotation.y = 0.0;
  58059. particle.rotation.z = 0.0;
  58060. particle.rotationQuaternion = null;
  58061. particle.scaling.x = 1.0;
  58062. particle.scaling.y = 1.0;
  58063. particle.scaling.z = 1.0;
  58064. particle.uvs.x = 0.0;
  58065. particle.uvs.y = 0.0;
  58066. particle.uvs.z = 1.0;
  58067. particle.uvs.w = 1.0;
  58068. particle.pivot.x = 0.0;
  58069. particle.pivot.y = 0.0;
  58070. particle.pivot.z = 0.0;
  58071. particle.translateFromPivot = false;
  58072. particle.parentId = null;
  58073. };
  58074. /**
  58075. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58076. * @returns the SPS.
  58077. */
  58078. SolidParticleSystem.prototype.rebuildMesh = function () {
  58079. for (var p = 0; p < this.particles.length; p++) {
  58080. this._rebuildParticle(this.particles[p]);
  58081. }
  58082. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58083. return this;
  58084. };
  58085. /**
  58086. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58087. * This method calls `updateParticle()` for each particle of the SPS.
  58088. * For an animated SPS, it is usually called within the render loop.
  58089. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58090. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58091. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58092. * @returns the SPS.
  58093. */
  58094. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58095. if (start === void 0) { start = 0; }
  58096. if (end === void 0) { end = this.nbParticles - 1; }
  58097. if (update === void 0) { update = true; }
  58098. if (!this._updatable) {
  58099. return this;
  58100. }
  58101. // custom beforeUpdate
  58102. this.beforeUpdateParticles(start, end, update);
  58103. this._cam_axisX.x = 1.0;
  58104. this._cam_axisX.y = 0.0;
  58105. this._cam_axisX.z = 0.0;
  58106. this._cam_axisY.x = 0.0;
  58107. this._cam_axisY.y = 1.0;
  58108. this._cam_axisY.z = 0.0;
  58109. this._cam_axisZ.x = 0.0;
  58110. this._cam_axisZ.y = 0.0;
  58111. this._cam_axisZ.z = 1.0;
  58112. // cases when the World Matrix is to be computed first
  58113. if (this.billboard || this._depthSort) {
  58114. this.mesh.computeWorldMatrix(true);
  58115. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58116. }
  58117. // if the particles will always face the camera
  58118. if (this.billboard) {
  58119. // compute the camera position and un-rotate it by the current mesh rotation
  58120. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58121. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58122. this._cam_axisZ.normalize();
  58123. // same for camera up vector extracted from the cam view matrix
  58124. var view = this._camera.getViewMatrix(true);
  58125. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58126. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58127. this._cam_axisY.normalize();
  58128. this._cam_axisX.normalize();
  58129. }
  58130. // if depthSort, compute the camera global position in the mesh local system
  58131. if (this._depthSort) {
  58132. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58133. }
  58134. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58135. var idx = 0; // current position index in the global array positions32
  58136. var index = 0; // position start index in the global array positions32 of the current particle
  58137. var colidx = 0; // current color index in the global array colors32
  58138. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58139. var uvidx = 0; // current uv index in the global array uvs32
  58140. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58141. var pt = 0; // current index in the particle model shape
  58142. if (this.mesh.isFacetDataEnabled) {
  58143. this._computeBoundingBox = true;
  58144. }
  58145. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58146. if (this._computeBoundingBox) {
  58147. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58148. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58149. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58150. }
  58151. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58152. if (this.mesh._boundingInfo) {
  58153. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58154. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58155. }
  58156. }
  58157. }
  58158. // particle loop
  58159. index = this.particles[start]._pos;
  58160. var vpos = (index / 3) | 0;
  58161. colorIndex = vpos * 4;
  58162. uvIndex = vpos * 2;
  58163. for (var p = start; p <= end; p++) {
  58164. this._particle = this.particles[p];
  58165. this._shape = this._particle._model._shape;
  58166. this._shapeUV = this._particle._model._shapeUV;
  58167. // call to custom user function to update the particle properties
  58168. this.updateParticle(this._particle);
  58169. // camera-particle distance for depth sorting
  58170. if (this._depthSort && this._depthSortParticles) {
  58171. var dsp = this.depthSortedParticles[p];
  58172. dsp.ind = this._particle._ind;
  58173. dsp.indicesLength = this._particle._model._indicesLength;
  58174. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58175. }
  58176. // skip the computations for inactive or already invisible particles
  58177. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58178. // increment indexes for the next particle
  58179. pt = this._shape.length;
  58180. index += pt * 3;
  58181. colorIndex += pt * 4;
  58182. uvIndex += pt * 2;
  58183. continue;
  58184. }
  58185. if (this._particle.isVisible) {
  58186. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58187. this._particleHasParent = (this._particle.parentId !== null);
  58188. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58189. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58190. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58191. // particle rotation matrix
  58192. if (this.billboard) {
  58193. this._particle.rotation.x = 0.0;
  58194. this._particle.rotation.y = 0.0;
  58195. }
  58196. if (this._computeParticleRotation || this.billboard) {
  58197. if (this._particle.rotationQuaternion) {
  58198. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58199. }
  58200. else {
  58201. this._yaw = this._particle.rotation.y;
  58202. this._pitch = this._particle.rotation.x;
  58203. this._roll = this._particle.rotation.z;
  58204. this._quaternionRotationYPR();
  58205. }
  58206. this._quaternionToRotationMatrix();
  58207. }
  58208. if (this._particleHasParent) {
  58209. this._parent = this.particles[this._particle.parentId];
  58210. 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];
  58211. 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];
  58212. 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];
  58213. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58214. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58215. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58216. if (this._computeParticleRotation || this.billboard) {
  58217. 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];
  58218. 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];
  58219. 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];
  58220. 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];
  58221. 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];
  58222. 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];
  58223. 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];
  58224. 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];
  58225. 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];
  58226. }
  58227. }
  58228. else {
  58229. this._particle._globalPosition.x = this._particle.position.x;
  58230. this._particle._globalPosition.y = this._particle.position.y;
  58231. this._particle._globalPosition.z = this._particle.position.z;
  58232. if (this._computeParticleRotation || this.billboard) {
  58233. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58234. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58235. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58236. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58237. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58238. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58239. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58240. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58241. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58242. }
  58243. }
  58244. if (this._particle.translateFromPivot) {
  58245. this._pivotBackTranslation.x = 0.0;
  58246. this._pivotBackTranslation.y = 0.0;
  58247. this._pivotBackTranslation.z = 0.0;
  58248. }
  58249. else {
  58250. this._pivotBackTranslation.x = this._scaledPivot.x;
  58251. this._pivotBackTranslation.y = this._scaledPivot.y;
  58252. this._pivotBackTranslation.z = this._scaledPivot.z;
  58253. }
  58254. // particle vertex loop
  58255. for (pt = 0; pt < this._shape.length; pt++) {
  58256. idx = index + pt * 3;
  58257. colidx = colorIndex + pt * 4;
  58258. uvidx = uvIndex + pt * 2;
  58259. this._vertex.x = this._shape[pt].x;
  58260. this._vertex.y = this._shape[pt].y;
  58261. this._vertex.z = this._shape[pt].z;
  58262. if (this._computeParticleVertex) {
  58263. this.updateParticleVertex(this._particle, this._vertex, pt);
  58264. }
  58265. // positions
  58266. this._vertex.x *= this._particle.scaling.x;
  58267. this._vertex.y *= this._particle.scaling.y;
  58268. this._vertex.z *= this._particle.scaling.z;
  58269. this._vertex.x -= this._scaledPivot.x;
  58270. this._vertex.y -= this._scaledPivot.y;
  58271. this._vertex.z -= this._scaledPivot.z;
  58272. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58273. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58274. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58275. this._rotated.x += this._pivotBackTranslation.x;
  58276. this._rotated.y += this._pivotBackTranslation.y;
  58277. this._rotated.z += this._pivotBackTranslation.z;
  58278. 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;
  58279. 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;
  58280. 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;
  58281. if (this._computeBoundingBox) {
  58282. if (this._positions32[idx] < this._minimum.x) {
  58283. this._minimum.x = this._positions32[idx];
  58284. }
  58285. if (this._positions32[idx] > this._maximum.x) {
  58286. this._maximum.x = this._positions32[idx];
  58287. }
  58288. if (this._positions32[idx + 1] < this._minimum.y) {
  58289. this._minimum.y = this._positions32[idx + 1];
  58290. }
  58291. if (this._positions32[idx + 1] > this._maximum.y) {
  58292. this._maximum.y = this._positions32[idx + 1];
  58293. }
  58294. if (this._positions32[idx + 2] < this._minimum.z) {
  58295. this._minimum.z = this._positions32[idx + 2];
  58296. }
  58297. if (this._positions32[idx + 2] > this._maximum.z) {
  58298. this._maximum.z = this._positions32[idx + 2];
  58299. }
  58300. }
  58301. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58302. if (!this._computeParticleVertex) {
  58303. this._normal.x = this._fixedNormal32[idx];
  58304. this._normal.y = this._fixedNormal32[idx + 1];
  58305. this._normal.z = this._fixedNormal32[idx + 2];
  58306. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58307. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58308. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58309. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58310. 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;
  58311. 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;
  58312. }
  58313. if (this._computeParticleColor && this._particle.color) {
  58314. this._colors32[colidx] = this._particle.color.r;
  58315. this._colors32[colidx + 1] = this._particle.color.g;
  58316. this._colors32[colidx + 2] = this._particle.color.b;
  58317. this._colors32[colidx + 3] = this._particle.color.a;
  58318. }
  58319. if (this._computeParticleTexture) {
  58320. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58321. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58322. }
  58323. }
  58324. }
  58325. // particle just set invisible : scaled to zero and positioned at the origin
  58326. else {
  58327. this._particle._stillInvisible = true; // mark the particle as invisible
  58328. for (pt = 0; pt < this._shape.length; pt++) {
  58329. idx = index + pt * 3;
  58330. colidx = colorIndex + pt * 4;
  58331. uvidx = uvIndex + pt * 2;
  58332. this._positions32[idx] = 0.0;
  58333. this._positions32[idx + 1] = 0.0;
  58334. this._positions32[idx + 2] = 0.0;
  58335. this._normals32[idx] = 0.0;
  58336. this._normals32[idx + 1] = 0.0;
  58337. this._normals32[idx + 2] = 0.0;
  58338. if (this._computeParticleColor && this._particle.color) {
  58339. this._colors32[colidx] = this._particle.color.r;
  58340. this._colors32[colidx + 1] = this._particle.color.g;
  58341. this._colors32[colidx + 2] = this._particle.color.b;
  58342. this._colors32[colidx + 3] = this._particle.color.a;
  58343. }
  58344. if (this._computeParticleTexture) {
  58345. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58346. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58347. }
  58348. }
  58349. }
  58350. // if the particle intersections must be computed : update the bbInfo
  58351. if (this._particlesIntersect) {
  58352. var bInfo = this._particle._boundingInfo;
  58353. var bBox = bInfo.boundingBox;
  58354. var bSphere = bInfo.boundingSphere;
  58355. if (!this._bSphereOnly) {
  58356. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58357. for (var b = 0; b < bBox.vectors.length; b++) {
  58358. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58359. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58360. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58361. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58362. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58363. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58364. 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;
  58365. 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;
  58366. 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;
  58367. }
  58368. bBox._update(this.mesh._worldMatrix);
  58369. }
  58370. // place and scale the particle bouding sphere in the SPS local system, then update it
  58371. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58372. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58373. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58374. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58375. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58376. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58377. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58378. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58379. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58380. 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));
  58381. bSphere._update(this.mesh._worldMatrix);
  58382. }
  58383. // increment indexes for the next particle
  58384. index = idx + 3;
  58385. colorIndex = colidx + 4;
  58386. uvIndex = uvidx + 2;
  58387. }
  58388. // if the VBO must be updated
  58389. if (update) {
  58390. if (this._computeParticleColor) {
  58391. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58392. }
  58393. if (this._computeParticleTexture) {
  58394. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58395. }
  58396. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58397. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58398. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58399. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58400. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58401. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58402. for (var i = 0; i < this._normals32.length; i++) {
  58403. this._fixedNormal32[i] = this._normals32[i];
  58404. }
  58405. }
  58406. if (!this.mesh.areNormalsFrozen) {
  58407. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58408. }
  58409. }
  58410. if (this._depthSort && this._depthSortParticles) {
  58411. this.depthSortedParticles.sort(this._depthSortFunction);
  58412. var dspl = this.depthSortedParticles.length;
  58413. var sorted = 0;
  58414. var lind = 0;
  58415. var sind = 0;
  58416. var sid = 0;
  58417. for (sorted = 0; sorted < dspl; sorted++) {
  58418. lind = this.depthSortedParticles[sorted].indicesLength;
  58419. sind = this.depthSortedParticles[sorted].ind;
  58420. for (var i = 0; i < lind; i++) {
  58421. this._indices32[sid] = this._indices[sind + i];
  58422. sid++;
  58423. }
  58424. }
  58425. this.mesh.updateIndices(this._indices32);
  58426. }
  58427. }
  58428. if (this._computeBoundingBox) {
  58429. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58430. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58431. }
  58432. this.afterUpdateParticles(start, end, update);
  58433. return this;
  58434. };
  58435. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58436. this._halfroll = this._roll * 0.5;
  58437. this._halfpitch = this._pitch * 0.5;
  58438. this._halfyaw = this._yaw * 0.5;
  58439. this._sinRoll = Math.sin(this._halfroll);
  58440. this._cosRoll = Math.cos(this._halfroll);
  58441. this._sinPitch = Math.sin(this._halfpitch);
  58442. this._cosPitch = Math.cos(this._halfpitch);
  58443. this._sinYaw = Math.sin(this._halfyaw);
  58444. this._cosYaw = Math.cos(this._halfyaw);
  58445. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58446. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58447. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58448. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58449. };
  58450. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58451. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58452. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58453. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58454. this._rotMatrix.m[3] = 0;
  58455. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58456. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58457. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58458. this._rotMatrix.m[7] = 0;
  58459. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58460. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58461. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58462. this._rotMatrix.m[11] = 0;
  58463. this._rotMatrix.m[12] = 0;
  58464. this._rotMatrix.m[13] = 0;
  58465. this._rotMatrix.m[14] = 0;
  58466. this._rotMatrix.m[15] = 1.0;
  58467. };
  58468. /**
  58469. * Disposes the SPS.
  58470. */
  58471. SolidParticleSystem.prototype.dispose = function () {
  58472. this.mesh.dispose();
  58473. this.vars = null;
  58474. // drop references to internal big arrays for the GC
  58475. this._positions = null;
  58476. this._indices = null;
  58477. this._normals = null;
  58478. this._uvs = null;
  58479. this._colors = null;
  58480. this._indices32 = null;
  58481. this._positions32 = null;
  58482. this._normals32 = null;
  58483. this._fixedNormal32 = null;
  58484. this._uvs32 = null;
  58485. this._colors32 = null;
  58486. this.pickedParticles = null;
  58487. };
  58488. /**
  58489. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58490. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58491. * @returns the SPS.
  58492. */
  58493. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58494. if (!this._isVisibilityBoxLocked) {
  58495. this.mesh.refreshBoundingInfo();
  58496. }
  58497. return this;
  58498. };
  58499. /**
  58500. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58501. * @param size the size (float) of the visibility box
  58502. * note : this doesn't lock the SPS mesh bounding box.
  58503. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58504. */
  58505. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58506. var vis = size / 2;
  58507. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58508. };
  58509. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58510. /**
  58511. * Gets whether the SPS as always visible or not
  58512. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58513. */
  58514. get: function () {
  58515. return this._alwaysVisible;
  58516. },
  58517. /**
  58518. * Sets the SPS as always visible or not
  58519. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58520. */
  58521. set: function (val) {
  58522. this._alwaysVisible = val;
  58523. this.mesh.alwaysSelectAsActiveMesh = val;
  58524. },
  58525. enumerable: true,
  58526. configurable: true
  58527. });
  58528. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58529. /**
  58530. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58531. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58532. */
  58533. get: function () {
  58534. return this._isVisibilityBoxLocked;
  58535. },
  58536. /**
  58537. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58538. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58539. */
  58540. set: function (val) {
  58541. this._isVisibilityBoxLocked = val;
  58542. var boundingInfo = this.mesh.getBoundingInfo();
  58543. boundingInfo.isLocked = val;
  58544. },
  58545. enumerable: true,
  58546. configurable: true
  58547. });
  58548. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58549. /**
  58550. * Gets if `setParticles()` computes the particle rotations or not.
  58551. * Default value : true. The SPS is faster when it's set to false.
  58552. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58553. */
  58554. get: function () {
  58555. return this._computeParticleRotation;
  58556. },
  58557. /**
  58558. * Tells to `setParticles()` to compute the particle rotations or not.
  58559. * Default value : true. The SPS is faster when it's set to false.
  58560. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58561. */
  58562. set: function (val) {
  58563. this._computeParticleRotation = val;
  58564. },
  58565. enumerable: true,
  58566. configurable: true
  58567. });
  58568. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58569. /**
  58570. * Gets if `setParticles()` computes the particle colors or not.
  58571. * Default value : true. The SPS is faster when it's set to false.
  58572. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58573. */
  58574. get: function () {
  58575. return this._computeParticleColor;
  58576. },
  58577. /**
  58578. * Tells to `setParticles()` to compute the particle colors or not.
  58579. * Default value : true. The SPS is faster when it's set to false.
  58580. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58581. */
  58582. set: function (val) {
  58583. this._computeParticleColor = val;
  58584. },
  58585. enumerable: true,
  58586. configurable: true
  58587. });
  58588. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58589. /**
  58590. * Gets if `setParticles()` computes the particle textures or not.
  58591. * Default value : true. The SPS is faster when it's set to false.
  58592. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58593. */
  58594. get: function () {
  58595. return this._computeParticleTexture;
  58596. },
  58597. set: function (val) {
  58598. this._computeParticleTexture = val;
  58599. },
  58600. enumerable: true,
  58601. configurable: true
  58602. });
  58603. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58604. /**
  58605. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58606. * Default value : false. The SPS is faster when it's set to false.
  58607. * Note : the particle custom vertex positions aren't stored values.
  58608. */
  58609. get: function () {
  58610. return this._computeParticleVertex;
  58611. },
  58612. /**
  58613. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58614. * Default value : false. The SPS is faster when it's set to false.
  58615. * Note : the particle custom vertex positions aren't stored values.
  58616. */
  58617. set: function (val) {
  58618. this._computeParticleVertex = val;
  58619. },
  58620. enumerable: true,
  58621. configurable: true
  58622. });
  58623. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58624. /**
  58625. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58626. */
  58627. get: function () {
  58628. return this._computeBoundingBox;
  58629. },
  58630. /**
  58631. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58632. */
  58633. set: function (val) {
  58634. this._computeBoundingBox = val;
  58635. },
  58636. enumerable: true,
  58637. configurable: true
  58638. });
  58639. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58640. /**
  58641. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58642. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58643. * Default : `true`
  58644. */
  58645. get: function () {
  58646. return this._depthSortParticles;
  58647. },
  58648. /**
  58649. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58650. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58651. * Default : `true`
  58652. */
  58653. set: function (val) {
  58654. this._depthSortParticles = val;
  58655. },
  58656. enumerable: true,
  58657. configurable: true
  58658. });
  58659. // =======================================================================
  58660. // Particle behavior logic
  58661. // these following methods may be overwritten by the user to fit his needs
  58662. /**
  58663. * This function does nothing. It may be overwritten to set all the particle first values.
  58664. * The SPS doesn't call this function, you may have to call it by your own.
  58665. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58666. */
  58667. SolidParticleSystem.prototype.initParticles = function () {
  58668. };
  58669. /**
  58670. * This function does nothing. It may be overwritten to recycle a particle.
  58671. * The SPS doesn't call this function, you may have to call it by your own.
  58672. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58673. * @param particle The particle to recycle
  58674. * @returns the recycled particle
  58675. */
  58676. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58677. return particle;
  58678. };
  58679. /**
  58680. * Updates a particle : this function should be overwritten by the user.
  58681. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58682. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58683. * @example : just set a particle position or velocity and recycle conditions
  58684. * @param particle The particle to update
  58685. * @returns the updated particle
  58686. */
  58687. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58688. return particle;
  58689. };
  58690. /**
  58691. * Updates a vertex of a particle : it can be overwritten by the user.
  58692. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58693. * @param particle the current particle
  58694. * @param vertex the current index of the current particle
  58695. * @param pt the index of the current vertex in the particle shape
  58696. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58697. * @example : just set a vertex particle position
  58698. * @returns the updated vertex
  58699. */
  58700. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58701. return vertex;
  58702. };
  58703. /**
  58704. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58705. * This does nothing and may be overwritten by the user.
  58706. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58707. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58708. * @param update the boolean update value actually passed to setParticles()
  58709. */
  58710. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58711. };
  58712. /**
  58713. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58714. * This will be passed three parameters.
  58715. * This does nothing and may be overwritten by the user.
  58716. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58717. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58718. * @param update the boolean update value actually passed to setParticles()
  58719. */
  58720. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58721. };
  58722. return SolidParticleSystem;
  58723. }());
  58724. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58725. })(BABYLON || (BABYLON = {}));
  58726. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58727. var BABYLON;
  58728. (function (BABYLON) {
  58729. var ShaderMaterial = /** @class */ (function (_super) {
  58730. __extends(ShaderMaterial, _super);
  58731. function ShaderMaterial(name, scene, shaderPath, options) {
  58732. var _this = _super.call(this, name, scene) || this;
  58733. _this._textures = {};
  58734. _this._textureArrays = {};
  58735. _this._floats = {};
  58736. _this._ints = {};
  58737. _this._floatsArrays = {};
  58738. _this._colors3 = {};
  58739. _this._colors3Arrays = {};
  58740. _this._colors4 = {};
  58741. _this._vectors2 = {};
  58742. _this._vectors3 = {};
  58743. _this._vectors4 = {};
  58744. _this._matrices = {};
  58745. _this._matrices3x3 = {};
  58746. _this._matrices2x2 = {};
  58747. _this._vectors2Arrays = {};
  58748. _this._vectors3Arrays = {};
  58749. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58750. _this._shaderPath = shaderPath;
  58751. options.needAlphaBlending = options.needAlphaBlending || false;
  58752. options.needAlphaTesting = options.needAlphaTesting || false;
  58753. options.attributes = options.attributes || ["position", "normal", "uv"];
  58754. options.uniforms = options.uniforms || ["worldViewProjection"];
  58755. options.uniformBuffers = options.uniformBuffers || [];
  58756. options.samplers = options.samplers || [];
  58757. options.defines = options.defines || [];
  58758. _this._options = options;
  58759. return _this;
  58760. }
  58761. ShaderMaterial.prototype.getClassName = function () {
  58762. return "ShaderMaterial";
  58763. };
  58764. ShaderMaterial.prototype.needAlphaBlending = function () {
  58765. return this._options.needAlphaBlending;
  58766. };
  58767. ShaderMaterial.prototype.needAlphaTesting = function () {
  58768. return this._options.needAlphaTesting;
  58769. };
  58770. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58771. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58772. this._options.uniforms.push(uniformName);
  58773. }
  58774. };
  58775. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58776. if (this._options.samplers.indexOf(name) === -1) {
  58777. this._options.samplers.push(name);
  58778. }
  58779. this._textures[name] = texture;
  58780. return this;
  58781. };
  58782. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58783. if (this._options.samplers.indexOf(name) === -1) {
  58784. this._options.samplers.push(name);
  58785. }
  58786. this._checkUniform(name);
  58787. this._textureArrays[name] = textures;
  58788. return this;
  58789. };
  58790. ShaderMaterial.prototype.setFloat = function (name, value) {
  58791. this._checkUniform(name);
  58792. this._floats[name] = value;
  58793. return this;
  58794. };
  58795. ShaderMaterial.prototype.setInt = function (name, value) {
  58796. this._checkUniform(name);
  58797. this._ints[name] = value;
  58798. return this;
  58799. };
  58800. ShaderMaterial.prototype.setFloats = function (name, value) {
  58801. this._checkUniform(name);
  58802. this._floatsArrays[name] = value;
  58803. return this;
  58804. };
  58805. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58806. this._checkUniform(name);
  58807. this._colors3[name] = value;
  58808. return this;
  58809. };
  58810. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58811. this._checkUniform(name);
  58812. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58813. color.toArray(arr, arr.length);
  58814. return arr;
  58815. }, []);
  58816. return this;
  58817. };
  58818. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58819. this._checkUniform(name);
  58820. this._colors4[name] = value;
  58821. return this;
  58822. };
  58823. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58824. this._checkUniform(name);
  58825. this._vectors2[name] = value;
  58826. return this;
  58827. };
  58828. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58829. this._checkUniform(name);
  58830. this._vectors3[name] = value;
  58831. return this;
  58832. };
  58833. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58834. this._checkUniform(name);
  58835. this._vectors4[name] = value;
  58836. return this;
  58837. };
  58838. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58839. this._checkUniform(name);
  58840. this._matrices[name] = value;
  58841. return this;
  58842. };
  58843. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58844. this._checkUniform(name);
  58845. this._matrices3x3[name] = value;
  58846. return this;
  58847. };
  58848. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58849. this._checkUniform(name);
  58850. this._matrices2x2[name] = value;
  58851. return this;
  58852. };
  58853. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58854. this._checkUniform(name);
  58855. this._vectors2Arrays[name] = value;
  58856. return this;
  58857. };
  58858. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58859. this._checkUniform(name);
  58860. this._vectors3Arrays[name] = value;
  58861. return this;
  58862. };
  58863. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58864. if (!mesh) {
  58865. return true;
  58866. }
  58867. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58868. return false;
  58869. }
  58870. return false;
  58871. };
  58872. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58873. var scene = this.getScene();
  58874. var engine = scene.getEngine();
  58875. if (!this.checkReadyOnEveryCall) {
  58876. if (this._renderId === scene.getRenderId()) {
  58877. if (this._checkCache(scene, mesh, useInstances)) {
  58878. return true;
  58879. }
  58880. }
  58881. }
  58882. // Instances
  58883. var defines = [];
  58884. var attribs = [];
  58885. var fallbacks = new BABYLON.EffectFallbacks();
  58886. if (useInstances) {
  58887. defines.push("#define INSTANCES");
  58888. }
  58889. for (var index = 0; index < this._options.defines.length; index++) {
  58890. defines.push(this._options.defines[index]);
  58891. }
  58892. for (var index = 0; index < this._options.attributes.length; index++) {
  58893. attribs.push(this._options.attributes[index]);
  58894. }
  58895. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58896. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58897. defines.push("#define VERTEXCOLOR");
  58898. }
  58899. // Bones
  58900. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58901. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58902. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58903. if (mesh.numBoneInfluencers > 4) {
  58904. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58905. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58906. }
  58907. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58908. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58909. fallbacks.addCPUSkinningFallback(0, mesh);
  58910. if (this._options.uniforms.indexOf("mBones") === -1) {
  58911. this._options.uniforms.push("mBones");
  58912. }
  58913. }
  58914. else {
  58915. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58916. }
  58917. // Textures
  58918. for (var name in this._textures) {
  58919. if (!this._textures[name].isReady()) {
  58920. return false;
  58921. }
  58922. }
  58923. // Alpha test
  58924. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58925. defines.push("#define ALPHATEST");
  58926. }
  58927. var previousEffect = this._effect;
  58928. var join = defines.join("\n");
  58929. this._effect = engine.createEffect(this._shaderPath, {
  58930. attributes: attribs,
  58931. uniformsNames: this._options.uniforms,
  58932. uniformBuffersNames: this._options.uniformBuffers,
  58933. samplers: this._options.samplers,
  58934. defines: join,
  58935. fallbacks: fallbacks,
  58936. onCompiled: this.onCompiled,
  58937. onError: this.onError
  58938. }, engine);
  58939. if (!this._effect.isReady()) {
  58940. return false;
  58941. }
  58942. if (previousEffect !== this._effect) {
  58943. scene.resetCachedMaterial();
  58944. }
  58945. this._renderId = scene.getRenderId();
  58946. return true;
  58947. };
  58948. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  58949. var scene = this.getScene();
  58950. if (!this._effect) {
  58951. return;
  58952. }
  58953. if (this._options.uniforms.indexOf("world") !== -1) {
  58954. this._effect.setMatrix("world", world);
  58955. }
  58956. if (this._options.uniforms.indexOf("worldView") !== -1) {
  58957. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  58958. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  58959. }
  58960. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  58961. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  58962. }
  58963. };
  58964. ShaderMaterial.prototype.bind = function (world, mesh) {
  58965. // Std values
  58966. this.bindOnlyWorldMatrix(world);
  58967. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  58968. if (this._options.uniforms.indexOf("view") !== -1) {
  58969. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  58970. }
  58971. if (this._options.uniforms.indexOf("projection") !== -1) {
  58972. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  58973. }
  58974. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  58975. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  58976. }
  58977. // Bones
  58978. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  58979. var name;
  58980. // Texture
  58981. for (name in this._textures) {
  58982. this._effect.setTexture(name, this._textures[name]);
  58983. }
  58984. // Texture arrays
  58985. for (name in this._textureArrays) {
  58986. this._effect.setTextureArray(name, this._textureArrays[name]);
  58987. }
  58988. // Int
  58989. for (name in this._ints) {
  58990. this._effect.setInt(name, this._ints[name]);
  58991. }
  58992. // Float
  58993. for (name in this._floats) {
  58994. this._effect.setFloat(name, this._floats[name]);
  58995. }
  58996. // Floats
  58997. for (name in this._floatsArrays) {
  58998. this._effect.setArray(name, this._floatsArrays[name]);
  58999. }
  59000. // Color3
  59001. for (name in this._colors3) {
  59002. this._effect.setColor3(name, this._colors3[name]);
  59003. }
  59004. for (name in this._colors3Arrays) {
  59005. this._effect.setArray3(name, this._colors3Arrays[name]);
  59006. }
  59007. // Color4
  59008. for (name in this._colors4) {
  59009. var color = this._colors4[name];
  59010. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59011. }
  59012. // Vector2
  59013. for (name in this._vectors2) {
  59014. this._effect.setVector2(name, this._vectors2[name]);
  59015. }
  59016. // Vector3
  59017. for (name in this._vectors3) {
  59018. this._effect.setVector3(name, this._vectors3[name]);
  59019. }
  59020. // Vector4
  59021. for (name in this._vectors4) {
  59022. this._effect.setVector4(name, this._vectors4[name]);
  59023. }
  59024. // Matrix
  59025. for (name in this._matrices) {
  59026. this._effect.setMatrix(name, this._matrices[name]);
  59027. }
  59028. // Matrix 3x3
  59029. for (name in this._matrices3x3) {
  59030. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59031. }
  59032. // Matrix 2x2
  59033. for (name in this._matrices2x2) {
  59034. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59035. }
  59036. // Vector2Array
  59037. for (name in this._vectors2Arrays) {
  59038. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59039. }
  59040. // Vector3Array
  59041. for (name in this._vectors3Arrays) {
  59042. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59043. }
  59044. }
  59045. this._afterBind(mesh);
  59046. };
  59047. ShaderMaterial.prototype.getActiveTextures = function () {
  59048. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59049. for (var name in this._textures) {
  59050. activeTextures.push(this._textures[name]);
  59051. }
  59052. for (var name in this._textureArrays) {
  59053. var array = this._textureArrays[name];
  59054. for (var index = 0; index < array.length; index++) {
  59055. activeTextures.push(array[index]);
  59056. }
  59057. }
  59058. return activeTextures;
  59059. };
  59060. ShaderMaterial.prototype.hasTexture = function (texture) {
  59061. if (_super.prototype.hasTexture.call(this, texture)) {
  59062. return true;
  59063. }
  59064. for (var name in this._textures) {
  59065. if (this._textures[name] === texture) {
  59066. return true;
  59067. }
  59068. }
  59069. for (var name in this._textureArrays) {
  59070. var array = this._textureArrays[name];
  59071. for (var index = 0; index < array.length; index++) {
  59072. if (array[index] === texture) {
  59073. return true;
  59074. }
  59075. }
  59076. }
  59077. return false;
  59078. };
  59079. ShaderMaterial.prototype.clone = function (name) {
  59080. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59081. return newShaderMaterial;
  59082. };
  59083. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59084. if (forceDisposeTextures) {
  59085. var name;
  59086. for (name in this._textures) {
  59087. this._textures[name].dispose();
  59088. }
  59089. for (name in this._textureArrays) {
  59090. var array = this._textureArrays[name];
  59091. for (var index = 0; index < array.length; index++) {
  59092. array[index].dispose();
  59093. }
  59094. }
  59095. }
  59096. this._textures = {};
  59097. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59098. };
  59099. ShaderMaterial.prototype.serialize = function () {
  59100. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59101. serializationObject.customType = "BABYLON.ShaderMaterial";
  59102. serializationObject.options = this._options;
  59103. serializationObject.shaderPath = this._shaderPath;
  59104. var name;
  59105. // Texture
  59106. serializationObject.textures = {};
  59107. for (name in this._textures) {
  59108. serializationObject.textures[name] = this._textures[name].serialize();
  59109. }
  59110. // Texture arrays
  59111. serializationObject.textureArrays = {};
  59112. for (name in this._textureArrays) {
  59113. serializationObject.textureArrays[name] = [];
  59114. var array = this._textureArrays[name];
  59115. for (var index = 0; index < array.length; index++) {
  59116. serializationObject.textureArrays[name].push(array[index].serialize());
  59117. }
  59118. }
  59119. // Float
  59120. serializationObject.floats = {};
  59121. for (name in this._floats) {
  59122. serializationObject.floats[name] = this._floats[name];
  59123. }
  59124. // Float s
  59125. serializationObject.FloatArrays = {};
  59126. for (name in this._floatsArrays) {
  59127. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59128. }
  59129. // Color3
  59130. serializationObject.colors3 = {};
  59131. for (name in this._colors3) {
  59132. serializationObject.colors3[name] = this._colors3[name].asArray();
  59133. }
  59134. // Color3 array
  59135. serializationObject.colors3Arrays = {};
  59136. for (name in this._colors3Arrays) {
  59137. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59138. }
  59139. // Color4
  59140. serializationObject.colors4 = {};
  59141. for (name in this._colors4) {
  59142. serializationObject.colors4[name] = this._colors4[name].asArray();
  59143. }
  59144. // Vector2
  59145. serializationObject.vectors2 = {};
  59146. for (name in this._vectors2) {
  59147. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59148. }
  59149. // Vector3
  59150. serializationObject.vectors3 = {};
  59151. for (name in this._vectors3) {
  59152. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59153. }
  59154. // Vector4
  59155. serializationObject.vectors4 = {};
  59156. for (name in this._vectors4) {
  59157. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59158. }
  59159. // Matrix
  59160. serializationObject.matrices = {};
  59161. for (name in this._matrices) {
  59162. serializationObject.matrices[name] = this._matrices[name].asArray();
  59163. }
  59164. // Matrix 3x3
  59165. serializationObject.matrices3x3 = {};
  59166. for (name in this._matrices3x3) {
  59167. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59168. }
  59169. // Matrix 2x2
  59170. serializationObject.matrices2x2 = {};
  59171. for (name in this._matrices2x2) {
  59172. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59173. }
  59174. // Vector2Array
  59175. serializationObject.vectors2Arrays = {};
  59176. for (name in this._vectors2Arrays) {
  59177. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59178. }
  59179. // Vector3Array
  59180. serializationObject.vectors3Arrays = {};
  59181. for (name in this._vectors3Arrays) {
  59182. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59183. }
  59184. return serializationObject;
  59185. };
  59186. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59187. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59188. var name;
  59189. // Texture
  59190. for (name in source.textures) {
  59191. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59192. }
  59193. // Texture arrays
  59194. for (name in source.textureArrays) {
  59195. var array = source.textureArrays[name];
  59196. var textureArray = new Array();
  59197. for (var index = 0; index < array.length; index++) {
  59198. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59199. }
  59200. material.setTextureArray(name, textureArray);
  59201. }
  59202. // Float
  59203. for (name in source.floats) {
  59204. material.setFloat(name, source.floats[name]);
  59205. }
  59206. // Float s
  59207. for (name in source.floatsArrays) {
  59208. material.setFloats(name, source.floatsArrays[name]);
  59209. }
  59210. // Color3
  59211. for (name in source.colors3) {
  59212. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59213. }
  59214. // Color3 arrays
  59215. for (name in source.colors3Arrays) {
  59216. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59217. if (i % 3 === 0) {
  59218. arr.push([num]);
  59219. }
  59220. else {
  59221. arr[arr.length - 1].push(num);
  59222. }
  59223. return arr;
  59224. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59225. material.setColor3Array(name, colors);
  59226. }
  59227. // Color4
  59228. for (name in source.colors4) {
  59229. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59230. }
  59231. // Vector2
  59232. for (name in source.vectors2) {
  59233. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59234. }
  59235. // Vector3
  59236. for (name in source.vectors3) {
  59237. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59238. }
  59239. // Vector4
  59240. for (name in source.vectors4) {
  59241. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59242. }
  59243. // Matrix
  59244. for (name in source.matrices) {
  59245. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59246. }
  59247. // Matrix 3x3
  59248. for (name in source.matrices3x3) {
  59249. material.setMatrix3x3(name, source.matrices3x3[name]);
  59250. }
  59251. // Matrix 2x2
  59252. for (name in source.matrices2x2) {
  59253. material.setMatrix2x2(name, source.matrices2x2[name]);
  59254. }
  59255. // Vector2Array
  59256. for (name in source.vectors2Arrays) {
  59257. material.setArray2(name, source.vectors2Arrays[name]);
  59258. }
  59259. // Vector3Array
  59260. for (name in source.vectors3Arrays) {
  59261. material.setArray3(name, source.vectors3Arrays[name]);
  59262. }
  59263. return material;
  59264. };
  59265. return ShaderMaterial;
  59266. }(BABYLON.Material));
  59267. BABYLON.ShaderMaterial = ShaderMaterial;
  59268. })(BABYLON || (BABYLON = {}));
  59269. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59270. var BABYLON;
  59271. (function (BABYLON) {
  59272. var GroundMesh = /** @class */ (function (_super) {
  59273. __extends(GroundMesh, _super);
  59274. function GroundMesh(name, scene) {
  59275. var _this = _super.call(this, name, scene) || this;
  59276. _this.generateOctree = false;
  59277. return _this;
  59278. }
  59279. GroundMesh.prototype.getClassName = function () {
  59280. return "GroundMesh";
  59281. };
  59282. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59283. get: function () {
  59284. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59285. },
  59286. enumerable: true,
  59287. configurable: true
  59288. });
  59289. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59290. get: function () {
  59291. return this._subdivisionsX;
  59292. },
  59293. enumerable: true,
  59294. configurable: true
  59295. });
  59296. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59297. get: function () {
  59298. return this._subdivisionsY;
  59299. },
  59300. enumerable: true,
  59301. configurable: true
  59302. });
  59303. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59304. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59305. this._subdivisionsX = chunksCount;
  59306. this._subdivisionsY = chunksCount;
  59307. this.subdivide(chunksCount);
  59308. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59309. };
  59310. /**
  59311. * Returns a height (y) value in the Worl system :
  59312. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59313. * Returns the ground y position if (x, z) are outside the ground surface.
  59314. */
  59315. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59316. var world = this.getWorldMatrix();
  59317. var invMat = BABYLON.Tmp.Matrix[5];
  59318. world.invertToRef(invMat);
  59319. var tmpVect = BABYLON.Tmp.Vector3[8];
  59320. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59321. x = tmpVect.x;
  59322. z = tmpVect.z;
  59323. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59324. return this.position.y;
  59325. }
  59326. if (!this._heightQuads || this._heightQuads.length == 0) {
  59327. this._initHeightQuads();
  59328. this._computeHeightQuads();
  59329. }
  59330. var facet = this._getFacetAt(x, z);
  59331. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59332. // return y in the World system
  59333. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59334. return tmpVect.y;
  59335. };
  59336. /**
  59337. * Returns a normalized vector (Vector3) orthogonal to the ground
  59338. * at the ground coordinates (x, z) expressed in the World system.
  59339. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59340. */
  59341. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59342. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59343. this.getNormalAtCoordinatesToRef(x, z, normal);
  59344. return normal;
  59345. };
  59346. /**
  59347. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59348. * at the ground coordinates (x, z) expressed in the World system.
  59349. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59350. * Returns the GroundMesh.
  59351. */
  59352. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59353. var world = this.getWorldMatrix();
  59354. var tmpMat = BABYLON.Tmp.Matrix[5];
  59355. world.invertToRef(tmpMat);
  59356. var tmpVect = BABYLON.Tmp.Vector3[8];
  59357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59358. x = tmpVect.x;
  59359. z = tmpVect.z;
  59360. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59361. return this;
  59362. }
  59363. if (!this._heightQuads || this._heightQuads.length == 0) {
  59364. this._initHeightQuads();
  59365. this._computeHeightQuads();
  59366. }
  59367. var facet = this._getFacetAt(x, z);
  59368. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59369. return this;
  59370. };
  59371. /**
  59372. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59373. * if the ground has been updated.
  59374. * This can be used in the render loop.
  59375. * Returns the GroundMesh.
  59376. */
  59377. GroundMesh.prototype.updateCoordinateHeights = function () {
  59378. if (!this._heightQuads || this._heightQuads.length == 0) {
  59379. this._initHeightQuads();
  59380. }
  59381. this._computeHeightQuads();
  59382. return this;
  59383. };
  59384. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59385. GroundMesh.prototype._getFacetAt = function (x, z) {
  59386. // retrieve col and row from x, z coordinates in the ground local system
  59387. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59388. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59389. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59390. var facet;
  59391. if (z < quad.slope.x * x + quad.slope.y) {
  59392. facet = quad.facet1;
  59393. }
  59394. else {
  59395. facet = quad.facet2;
  59396. }
  59397. return facet;
  59398. };
  59399. // Creates and populates the heightMap array with "facet" elements :
  59400. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59401. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59402. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59403. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59404. // Returns the GroundMesh.
  59405. GroundMesh.prototype._initHeightQuads = function () {
  59406. var subdivisionsX = this._subdivisionsX;
  59407. var subdivisionsY = this._subdivisionsY;
  59408. this._heightQuads = new Array();
  59409. for (var row = 0; row < subdivisionsY; row++) {
  59410. for (var col = 0; col < subdivisionsX; col++) {
  59411. 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) };
  59412. this._heightQuads[row * subdivisionsX + col] = quad;
  59413. }
  59414. }
  59415. return this;
  59416. };
  59417. // Compute each quad element values and update the the heightMap array :
  59418. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59419. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59420. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59421. // Returns the GroundMesh.
  59422. GroundMesh.prototype._computeHeightQuads = function () {
  59423. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59424. if (!positions) {
  59425. return this;
  59426. }
  59427. var v1 = BABYLON.Tmp.Vector3[3];
  59428. var v2 = BABYLON.Tmp.Vector3[2];
  59429. var v3 = BABYLON.Tmp.Vector3[1];
  59430. var v4 = BABYLON.Tmp.Vector3[0];
  59431. var v1v2 = BABYLON.Tmp.Vector3[4];
  59432. var v1v3 = BABYLON.Tmp.Vector3[5];
  59433. var v1v4 = BABYLON.Tmp.Vector3[6];
  59434. var norm1 = BABYLON.Tmp.Vector3[7];
  59435. var norm2 = BABYLON.Tmp.Vector3[8];
  59436. var i = 0;
  59437. var j = 0;
  59438. var k = 0;
  59439. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59440. var h = 0;
  59441. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59442. var d2 = 0;
  59443. var subdivisionsX = this._subdivisionsX;
  59444. var subdivisionsY = this._subdivisionsY;
  59445. for (var row = 0; row < subdivisionsY; row++) {
  59446. for (var col = 0; col < subdivisionsX; col++) {
  59447. i = col * 3;
  59448. j = row * (subdivisionsX + 1) * 3;
  59449. k = (row + 1) * (subdivisionsX + 1) * 3;
  59450. v1.x = positions[j + i];
  59451. v1.y = positions[j + i + 1];
  59452. v1.z = positions[j + i + 2];
  59453. v2.x = positions[j + i + 3];
  59454. v2.y = positions[j + i + 4];
  59455. v2.z = positions[j + i + 5];
  59456. v3.x = positions[k + i];
  59457. v3.y = positions[k + i + 1];
  59458. v3.z = positions[k + i + 2];
  59459. v4.x = positions[k + i + 3];
  59460. v4.y = positions[k + i + 4];
  59461. v4.z = positions[k + i + 5];
  59462. // 2D slope V1V4
  59463. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59464. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59465. // facet equations :
  59466. // we compute each facet normal vector
  59467. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59468. // we compute the value d by applying the equation to v1 which belongs to the plane
  59469. // then we store the facet equation in a Vector4
  59470. v2.subtractToRef(v1, v1v2);
  59471. v3.subtractToRef(v1, v1v3);
  59472. v4.subtractToRef(v1, v1v4);
  59473. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59474. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59475. norm1.normalize();
  59476. norm2.normalize();
  59477. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59478. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59479. var quad = this._heightQuads[row * subdivisionsX + col];
  59480. quad.slope.copyFromFloats(cd, h);
  59481. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59482. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59483. }
  59484. }
  59485. return this;
  59486. };
  59487. GroundMesh.prototype.serialize = function (serializationObject) {
  59488. _super.prototype.serialize.call(this, serializationObject);
  59489. serializationObject.subdivisionsX = this._subdivisionsX;
  59490. serializationObject.subdivisionsY = this._subdivisionsY;
  59491. serializationObject.minX = this._minX;
  59492. serializationObject.maxX = this._maxX;
  59493. serializationObject.minZ = this._minZ;
  59494. serializationObject.maxZ = this._maxZ;
  59495. serializationObject.width = this._width;
  59496. serializationObject.height = this._height;
  59497. };
  59498. GroundMesh.Parse = function (parsedMesh, scene) {
  59499. var result = new GroundMesh(parsedMesh.name, scene);
  59500. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59501. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59502. result._minX = parsedMesh.minX;
  59503. result._maxX = parsedMesh.maxX;
  59504. result._minZ = parsedMesh.minZ;
  59505. result._maxZ = parsedMesh.maxZ;
  59506. result._width = parsedMesh.width;
  59507. result._height = parsedMesh.height;
  59508. return result;
  59509. };
  59510. return GroundMesh;
  59511. }(BABYLON.Mesh));
  59512. BABYLON.GroundMesh = GroundMesh;
  59513. })(BABYLON || (BABYLON = {}));
  59514. //# sourceMappingURL=babylon.groundMesh.js.map
  59515. var BABYLON;
  59516. (function (BABYLON) {
  59517. /**
  59518. * Creates an instance based on a source mesh.
  59519. */
  59520. var InstancedMesh = /** @class */ (function (_super) {
  59521. __extends(InstancedMesh, _super);
  59522. function InstancedMesh(name, source) {
  59523. var _this = _super.call(this, name, source.getScene()) || this;
  59524. source.instances.push(_this);
  59525. _this._sourceMesh = source;
  59526. _this.position.copyFrom(source.position);
  59527. _this.rotation.copyFrom(source.rotation);
  59528. _this.scaling.copyFrom(source.scaling);
  59529. if (source.rotationQuaternion) {
  59530. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59531. }
  59532. _this.infiniteDistance = source.infiniteDistance;
  59533. _this.setPivotMatrix(source.getPivotMatrix());
  59534. _this.refreshBoundingInfo();
  59535. _this._syncSubMeshes();
  59536. return _this;
  59537. }
  59538. /**
  59539. * Returns the string "InstancedMesh".
  59540. */
  59541. InstancedMesh.prototype.getClassName = function () {
  59542. return "InstancedMesh";
  59543. };
  59544. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59545. // Methods
  59546. get: function () {
  59547. return this._sourceMesh.receiveShadows;
  59548. },
  59549. enumerable: true,
  59550. configurable: true
  59551. });
  59552. Object.defineProperty(InstancedMesh.prototype, "material", {
  59553. get: function () {
  59554. return this._sourceMesh.material;
  59555. },
  59556. enumerable: true,
  59557. configurable: true
  59558. });
  59559. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59560. get: function () {
  59561. return this._sourceMesh.visibility;
  59562. },
  59563. enumerable: true,
  59564. configurable: true
  59565. });
  59566. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59567. get: function () {
  59568. return this._sourceMesh.skeleton;
  59569. },
  59570. enumerable: true,
  59571. configurable: true
  59572. });
  59573. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59574. get: function () {
  59575. return this._sourceMesh.renderingGroupId;
  59576. },
  59577. set: function (value) {
  59578. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59579. return;
  59580. }
  59581. //no-op with warning
  59582. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59583. },
  59584. enumerable: true,
  59585. configurable: true
  59586. });
  59587. /**
  59588. * Returns the total number of vertices (integer).
  59589. */
  59590. InstancedMesh.prototype.getTotalVertices = function () {
  59591. return this._sourceMesh.getTotalVertices();
  59592. };
  59593. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59594. get: function () {
  59595. return this._sourceMesh;
  59596. },
  59597. enumerable: true,
  59598. configurable: true
  59599. });
  59600. /**
  59601. * Is this node ready to be used/rendered
  59602. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59603. * @return {boolean} is it ready
  59604. */
  59605. InstancedMesh.prototype.isReady = function (completeCheck) {
  59606. if (completeCheck === void 0) { completeCheck = false; }
  59607. return this._sourceMesh.isReady(completeCheck, true);
  59608. };
  59609. /**
  59610. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59611. */
  59612. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59613. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59614. };
  59615. /**
  59616. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59617. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59618. * The `data` are either a numeric array either a Float32Array.
  59619. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59620. * 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).
  59621. * Note that a new underlying VertexBuffer object is created each call.
  59622. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59623. *
  59624. * Possible `kind` values :
  59625. * - BABYLON.VertexBuffer.PositionKind
  59626. * - BABYLON.VertexBuffer.UVKind
  59627. * - BABYLON.VertexBuffer.UV2Kind
  59628. * - BABYLON.VertexBuffer.UV3Kind
  59629. * - BABYLON.VertexBuffer.UV4Kind
  59630. * - BABYLON.VertexBuffer.UV5Kind
  59631. * - BABYLON.VertexBuffer.UV6Kind
  59632. * - BABYLON.VertexBuffer.ColorKind
  59633. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59634. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59635. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59636. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59637. *
  59638. * Returns the Mesh.
  59639. */
  59640. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59641. if (this.sourceMesh) {
  59642. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59643. }
  59644. return this.sourceMesh;
  59645. };
  59646. /**
  59647. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59648. * If the mesh has no geometry, it is simply returned as it is.
  59649. * The `data` are either a numeric array either a Float32Array.
  59650. * No new underlying VertexBuffer object is created.
  59651. * 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.
  59652. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59653. *
  59654. * Possible `kind` values :
  59655. * - BABYLON.VertexBuffer.PositionKind
  59656. * - BABYLON.VertexBuffer.UVKind
  59657. * - BABYLON.VertexBuffer.UV2Kind
  59658. * - BABYLON.VertexBuffer.UV3Kind
  59659. * - BABYLON.VertexBuffer.UV4Kind
  59660. * - BABYLON.VertexBuffer.UV5Kind
  59661. * - BABYLON.VertexBuffer.UV6Kind
  59662. * - BABYLON.VertexBuffer.ColorKind
  59663. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59664. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59665. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59666. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59667. *
  59668. * Returns the Mesh.
  59669. */
  59670. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59671. if (this.sourceMesh) {
  59672. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59673. }
  59674. return this.sourceMesh;
  59675. };
  59676. /**
  59677. * Sets the mesh indices.
  59678. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59679. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59680. * This method creates a new index buffer each call.
  59681. * Returns the Mesh.
  59682. */
  59683. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59684. if (totalVertices === void 0) { totalVertices = null; }
  59685. if (this.sourceMesh) {
  59686. this.sourceMesh.setIndices(indices, totalVertices);
  59687. }
  59688. return this.sourceMesh;
  59689. };
  59690. /**
  59691. * Boolean : True if the mesh owns the requested kind of data.
  59692. */
  59693. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59694. return this._sourceMesh.isVerticesDataPresent(kind);
  59695. };
  59696. /**
  59697. * Returns an array of indices (IndicesArray).
  59698. */
  59699. InstancedMesh.prototype.getIndices = function () {
  59700. return this._sourceMesh.getIndices();
  59701. };
  59702. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59703. get: function () {
  59704. return this._sourceMesh._positions;
  59705. },
  59706. enumerable: true,
  59707. configurable: true
  59708. });
  59709. /**
  59710. * Sets a new updated BoundingInfo to the mesh.
  59711. * Returns the mesh.
  59712. */
  59713. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59714. var meshBB = this._sourceMesh.getBoundingInfo();
  59715. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59716. this._updateBoundingInfo();
  59717. return this;
  59718. };
  59719. InstancedMesh.prototype._preActivate = function () {
  59720. if (this._currentLOD) {
  59721. this._currentLOD._preActivate();
  59722. }
  59723. return this;
  59724. };
  59725. InstancedMesh.prototype._activate = function (renderId) {
  59726. if (this._currentLOD) {
  59727. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59728. }
  59729. return this;
  59730. };
  59731. /**
  59732. * Returns the current associated LOD AbstractMesh.
  59733. */
  59734. InstancedMesh.prototype.getLOD = function (camera) {
  59735. if (!camera) {
  59736. return this;
  59737. }
  59738. var boundingInfo = this.getBoundingInfo();
  59739. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59740. if (this._currentLOD === this.sourceMesh) {
  59741. return this;
  59742. }
  59743. return this._currentLOD;
  59744. };
  59745. InstancedMesh.prototype._syncSubMeshes = function () {
  59746. this.releaseSubMeshes();
  59747. if (this._sourceMesh.subMeshes) {
  59748. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59749. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59750. }
  59751. }
  59752. return this;
  59753. };
  59754. InstancedMesh.prototype._generatePointsArray = function () {
  59755. return this._sourceMesh._generatePointsArray();
  59756. };
  59757. /**
  59758. * Creates a new InstancedMesh from the current mesh.
  59759. * - name (string) : the cloned mesh name
  59760. * - newParent (optional Node) : the optional Node to parent the clone to.
  59761. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59762. *
  59763. * Returns the clone.
  59764. */
  59765. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59766. var result = this._sourceMesh.createInstance(name);
  59767. // Deep copy
  59768. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59769. // Bounding info
  59770. this.refreshBoundingInfo();
  59771. // Parent
  59772. if (newParent) {
  59773. result.parent = newParent;
  59774. }
  59775. if (!doNotCloneChildren) {
  59776. // Children
  59777. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59778. var mesh = this.getScene().meshes[index];
  59779. if (mesh.parent === this) {
  59780. mesh.clone(mesh.name, result);
  59781. }
  59782. }
  59783. }
  59784. result.computeWorldMatrix(true);
  59785. return result;
  59786. };
  59787. /**
  59788. * Disposes the InstancedMesh.
  59789. * Returns nothing.
  59790. */
  59791. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59792. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59793. // Remove from mesh
  59794. var index = this._sourceMesh.instances.indexOf(this);
  59795. this._sourceMesh.instances.splice(index, 1);
  59796. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59797. };
  59798. return InstancedMesh;
  59799. }(BABYLON.AbstractMesh));
  59800. BABYLON.InstancedMesh = InstancedMesh;
  59801. })(BABYLON || (BABYLON = {}));
  59802. //# sourceMappingURL=babylon.instancedMesh.js.map
  59803. var BABYLON;
  59804. (function (BABYLON) {
  59805. var LinesMesh = /** @class */ (function (_super) {
  59806. __extends(LinesMesh, _super);
  59807. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59808. if (scene === void 0) { scene = null; }
  59809. if (parent === void 0) { parent = null; }
  59810. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59811. _this.useVertexColor = useVertexColor;
  59812. _this.useVertexAlpha = useVertexAlpha;
  59813. _this.color = new BABYLON.Color3(1, 1, 1);
  59814. _this.alpha = 1;
  59815. if (source) {
  59816. _this.color = source.color.clone();
  59817. _this.alpha = source.alpha;
  59818. _this.useVertexColor = source.useVertexColor;
  59819. _this.useVertexAlpha = source.useVertexAlpha;
  59820. }
  59821. _this._intersectionThreshold = 0.1;
  59822. var defines = [];
  59823. var options = {
  59824. attributes: [BABYLON.VertexBuffer.PositionKind],
  59825. uniforms: ["world", "viewProjection"],
  59826. needAlphaBlending: true,
  59827. defines: defines
  59828. };
  59829. if (useVertexAlpha === false) {
  59830. options.needAlphaBlending = false;
  59831. }
  59832. if (!useVertexColor) {
  59833. options.uniforms.push("color");
  59834. }
  59835. else {
  59836. options.defines.push("#define VERTEXCOLOR");
  59837. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59838. }
  59839. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59840. return _this;
  59841. }
  59842. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59843. /**
  59844. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59845. * This margin is expressed in world space coordinates, so its value may vary.
  59846. * Default value is 0.1
  59847. * @returns the intersection Threshold value.
  59848. */
  59849. get: function () {
  59850. return this._intersectionThreshold;
  59851. },
  59852. /**
  59853. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59854. * This margin is expressed in world space coordinates, so its value may vary.
  59855. * @param value the new threshold to apply
  59856. */
  59857. set: function (value) {
  59858. if (this._intersectionThreshold === value) {
  59859. return;
  59860. }
  59861. this._intersectionThreshold = value;
  59862. if (this.geometry) {
  59863. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59864. }
  59865. },
  59866. enumerable: true,
  59867. configurable: true
  59868. });
  59869. /**
  59870. * Returns the string "LineMesh"
  59871. */
  59872. LinesMesh.prototype.getClassName = function () {
  59873. return "LinesMesh";
  59874. };
  59875. Object.defineProperty(LinesMesh.prototype, "material", {
  59876. get: function () {
  59877. return this._colorShader;
  59878. },
  59879. set: function (value) {
  59880. // Do nothing
  59881. },
  59882. enumerable: true,
  59883. configurable: true
  59884. });
  59885. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59886. get: function () {
  59887. return false;
  59888. },
  59889. enumerable: true,
  59890. configurable: true
  59891. });
  59892. LinesMesh.prototype.createInstance = function (name) {
  59893. throw new Error("LinesMeshes do not support createInstance.");
  59894. };
  59895. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59896. if (!this._geometry) {
  59897. return this;
  59898. }
  59899. // VBOs
  59900. this._geometry._bind(this._colorShader.getEffect());
  59901. // Color
  59902. if (!this.useVertexColor) {
  59903. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59904. }
  59905. return this;
  59906. };
  59907. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59908. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59909. return this;
  59910. }
  59911. var engine = this.getScene().getEngine();
  59912. // Draw order
  59913. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59914. return this;
  59915. };
  59916. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59917. this._colorShader.dispose();
  59918. _super.prototype.dispose.call(this, doNotRecurse);
  59919. };
  59920. /**
  59921. * Returns a new LineMesh object cloned from the current one.
  59922. */
  59923. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59924. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59925. };
  59926. return LinesMesh;
  59927. }(BABYLON.Mesh));
  59928. BABYLON.LinesMesh = LinesMesh;
  59929. })(BABYLON || (BABYLON = {}));
  59930. //# sourceMappingURL=babylon.linesMesh.js.map
  59931. var BABYLON;
  59932. (function (BABYLON) {
  59933. /**
  59934. * Class containing static functions to help procedurally build meshes
  59935. */
  59936. var MeshBuilder = /** @class */ (function () {
  59937. function MeshBuilder() {
  59938. }
  59939. MeshBuilder.updateSideOrientation = function (orientation) {
  59940. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  59941. return BABYLON.Mesh.DOUBLESIDE;
  59942. }
  59943. if (orientation === undefined || orientation === null) {
  59944. return BABYLON.Mesh.FRONTSIDE;
  59945. }
  59946. return orientation;
  59947. };
  59948. /**
  59949. * Creates a box mesh
  59950. * * The parameter `size` sets the size (float) of each box side (default 1)
  59951. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  59952. * * 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)
  59953. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  59954. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59955. * * 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
  59956. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59957. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  59958. * @param name defines the name of the mesh
  59959. * @param options defines the options used to create the mesh
  59960. * @param scene defines the hosting scene
  59961. * @returns the box mesh
  59962. */
  59963. MeshBuilder.CreateBox = function (name, options, scene) {
  59964. if (scene === void 0) { scene = null; }
  59965. var box = new BABYLON.Mesh(name, scene);
  59966. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59967. box._originalBuilderSideOrientation = options.sideOrientation;
  59968. var vertexData = BABYLON.VertexData.CreateBox(options);
  59969. vertexData.applyToMesh(box, options.updatable);
  59970. return box;
  59971. };
  59972. /**
  59973. * Creates a sphere mesh
  59974. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  59975. * * 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`)
  59976. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  59977. * * 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
  59978. * * 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)
  59979. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  59980. * * 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
  59981. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  59982. * @param name defines the name of the mesh
  59983. * @param options defines the options used to create the mesh
  59984. * @param scene defines the hosting scene
  59985. * @returns the sphere mesh
  59986. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  59987. */
  59988. MeshBuilder.CreateSphere = function (name, options, scene) {
  59989. var sphere = new BABYLON.Mesh(name, scene);
  59990. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  59991. sphere._originalBuilderSideOrientation = options.sideOrientation;
  59992. var vertexData = BABYLON.VertexData.CreateSphere(options);
  59993. vertexData.applyToMesh(sphere, options.updatable);
  59994. return sphere;
  59995. };
  59996. /**
  59997. * Creates a plane polygonal mesh. By default, this is a disc
  59998. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  59999. * * 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
  60000. * * 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
  60001. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60002. * * 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
  60003. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60004. * @param name defines the name of the mesh
  60005. * @param options defines the options used to create the mesh
  60006. * @param scene defines the hosting scene
  60007. * @returns the plane polygonal mesh
  60008. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60009. */
  60010. MeshBuilder.CreateDisc = function (name, options, scene) {
  60011. if (scene === void 0) { scene = null; }
  60012. var disc = new BABYLON.Mesh(name, scene);
  60013. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60014. disc._originalBuilderSideOrientation = options.sideOrientation;
  60015. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60016. vertexData.applyToMesh(disc, options.updatable);
  60017. return disc;
  60018. };
  60019. /**
  60020. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60021. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60022. * * 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`)
  60023. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60024. * * 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
  60025. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60026. * * 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
  60027. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60028. * @param name defines the name of the mesh
  60029. * @param options defines the options used to create the mesh
  60030. * @param scene defines the hosting scene
  60031. * @returns the icosahedron mesh
  60032. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60033. */
  60034. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60035. var sphere = new BABYLON.Mesh(name, scene);
  60036. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60037. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60038. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60039. vertexData.applyToMesh(sphere, options.updatable);
  60040. return sphere;
  60041. };
  60042. ;
  60043. /**
  60044. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60045. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60046. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60047. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60048. * * 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
  60049. * * 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
  60050. * * 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
  60051. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60052. * * 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
  60053. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60054. * * 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
  60055. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60056. * * 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
  60057. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60058. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60059. * @param name defines the name of the mesh
  60060. * @param options defines the options used to create the mesh
  60061. * @param scene defines the hosting scene
  60062. * @returns the ribbon mesh
  60063. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60064. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60065. */
  60066. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60067. if (scene === void 0) { scene = null; }
  60068. var pathArray = options.pathArray;
  60069. var closeArray = options.closeArray;
  60070. var closePath = options.closePath;
  60071. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60072. var instance = options.instance;
  60073. var updatable = options.updatable;
  60074. if (instance) { // existing ribbon instance update
  60075. // positionFunction : ribbon case
  60076. // only pathArray and sideOrientation parameters are taken into account for positions update
  60077. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60078. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60079. var positionFunction = function (positions) {
  60080. var minlg = pathArray[0].length;
  60081. var i = 0;
  60082. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60083. for (var si = 1; si <= ns; si++) {
  60084. for (var p = 0; p < pathArray.length; p++) {
  60085. var path = pathArray[p];
  60086. var l = path.length;
  60087. minlg = (minlg < l) ? minlg : l;
  60088. var j = 0;
  60089. while (j < minlg) {
  60090. positions[i] = path[j].x;
  60091. positions[i + 1] = path[j].y;
  60092. positions[i + 2] = path[j].z;
  60093. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60094. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60095. }
  60096. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60097. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60098. }
  60099. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60100. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60101. }
  60102. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60103. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60104. }
  60105. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60106. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60107. }
  60108. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60109. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60110. }
  60111. j++;
  60112. i += 3;
  60113. }
  60114. if (instance._closePath) {
  60115. positions[i] = path[0].x;
  60116. positions[i + 1] = path[0].y;
  60117. positions[i + 2] = path[0].z;
  60118. i += 3;
  60119. }
  60120. }
  60121. }
  60122. };
  60123. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60124. positionFunction(positions);
  60125. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60126. instance._boundingInfo.update(instance._worldMatrix);
  60127. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60128. if (options.colors) {
  60129. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60130. for (var c = 0; c < options.colors.length; c++) {
  60131. colors[c * 4] = options.colors[c].r;
  60132. colors[c * 4 + 1] = options.colors[c].g;
  60133. colors[c * 4 + 2] = options.colors[c].b;
  60134. colors[c * 4 + 3] = options.colors[c].a;
  60135. }
  60136. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60137. }
  60138. if (options.uvs) {
  60139. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60140. for (var i = 0; i < options.uvs.length; i++) {
  60141. uvs[i * 2] = options.uvs[i].x;
  60142. uvs[i * 2 + 1] = options.uvs[i].y;
  60143. }
  60144. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60145. }
  60146. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60147. var indices = instance.getIndices();
  60148. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60149. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60150. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60151. if (instance._closePath) {
  60152. var indexFirst = 0;
  60153. var indexLast = 0;
  60154. for (var p = 0; p < pathArray.length; p++) {
  60155. indexFirst = instance._idx[p] * 3;
  60156. if (p + 1 < pathArray.length) {
  60157. indexLast = (instance._idx[p + 1] - 1) * 3;
  60158. }
  60159. else {
  60160. indexLast = normals.length - 3;
  60161. }
  60162. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60163. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60164. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60165. normals[indexLast] = normals[indexFirst];
  60166. normals[indexLast + 1] = normals[indexFirst + 1];
  60167. normals[indexLast + 2] = normals[indexFirst + 2];
  60168. }
  60169. }
  60170. if (!(instance.areNormalsFrozen)) {
  60171. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60172. }
  60173. }
  60174. return instance;
  60175. }
  60176. else { // new ribbon creation
  60177. var ribbon = new BABYLON.Mesh(name, scene);
  60178. ribbon._originalBuilderSideOrientation = sideOrientation;
  60179. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60180. if (closePath) {
  60181. ribbon._idx = vertexData._idx;
  60182. }
  60183. ribbon._closePath = closePath;
  60184. ribbon._closeArray = closeArray;
  60185. vertexData.applyToMesh(ribbon, updatable);
  60186. return ribbon;
  60187. }
  60188. };
  60189. /**
  60190. * Creates a cylinder or a cone mesh
  60191. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60192. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60193. * * 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.
  60194. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60195. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60196. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60197. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60198. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60199. * * 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).
  60200. * * 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
  60201. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60202. * * 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
  60203. * * 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.
  60204. * * If `enclose` is false, a ring surface is one element.
  60205. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60206. * * 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
  60207. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60208. * * 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
  60209. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60210. * @param name defines the name of the mesh
  60211. * @param options defines the options used to create the mesh
  60212. * @param scene defines the hosting scene
  60213. * @returns the cylinder mesh
  60214. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60215. */
  60216. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60217. var cylinder = new BABYLON.Mesh(name, scene);
  60218. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60219. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60220. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60221. vertexData.applyToMesh(cylinder, options.updatable);
  60222. return cylinder;
  60223. };
  60224. /**
  60225. * Creates a torus mesh
  60226. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60227. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60228. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60229. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60230. * * 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
  60231. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60232. * @param name defines the name of the mesh
  60233. * @param options defines the options used to create the mesh
  60234. * @param scene defines the hosting scene
  60235. * @returns the torus mesh
  60236. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60237. */
  60238. MeshBuilder.CreateTorus = function (name, options, scene) {
  60239. var torus = new BABYLON.Mesh(name, scene);
  60240. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60241. torus._originalBuilderSideOrientation = options.sideOrientation;
  60242. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60243. vertexData.applyToMesh(torus, options.updatable);
  60244. return torus;
  60245. };
  60246. /**
  60247. * Creates a torus knot mesh
  60248. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60249. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60250. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60251. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60252. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60253. * * 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
  60254. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60255. * @param name defines the name of the mesh
  60256. * @param options defines the options used to create the mesh
  60257. * @param scene defines the hosting scene
  60258. * @returns the torus knot mesh
  60259. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60260. */
  60261. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60262. var torusKnot = new BABYLON.Mesh(name, scene);
  60263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60264. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60265. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60266. vertexData.applyToMesh(torusKnot, options.updatable);
  60267. return torusKnot;
  60268. };
  60269. /**
  60270. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60271. * * 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
  60272. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60273. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60274. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60275. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60276. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60277. * * 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
  60278. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60279. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60280. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60281. * @param name defines the name of the new line system
  60282. * @param options defines the options used to create the line system
  60283. * @param scene defines the hosting scene
  60284. * @returns a new line system mesh
  60285. */
  60286. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60287. var instance = options.instance;
  60288. var lines = options.lines;
  60289. var colors = options.colors;
  60290. if (instance) { // lines update
  60291. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60292. var vertexColor;
  60293. var lineColors;
  60294. if (colors) {
  60295. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60296. }
  60297. var i = 0;
  60298. var c = 0;
  60299. for (var l = 0; l < lines.length; l++) {
  60300. var points = lines[l];
  60301. for (var p = 0; p < points.length; p++) {
  60302. positions[i] = points[p].x;
  60303. positions[i + 1] = points[p].y;
  60304. positions[i + 2] = points[p].z;
  60305. if (colors && vertexColor) {
  60306. lineColors = colors[l];
  60307. vertexColor[c] = lineColors[p].r;
  60308. vertexColor[c + 1] = lineColors[p].g;
  60309. vertexColor[c + 2] = lineColors[p].b;
  60310. vertexColor[c + 3] = lineColors[p].a;
  60311. c += 4;
  60312. }
  60313. i += 3;
  60314. }
  60315. }
  60316. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60317. if (colors && vertexColor) {
  60318. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60319. }
  60320. return instance;
  60321. }
  60322. // line system creation
  60323. var useVertexColor = (colors) ? true : false;
  60324. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60325. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60326. vertexData.applyToMesh(lineSystem, options.updatable);
  60327. return lineSystem;
  60328. };
  60329. /**
  60330. * Creates a line mesh
  60331. * 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
  60332. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60333. * * The parameter `points` is an array successive Vector3
  60334. * * 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
  60335. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60336. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60337. * * When updating an instance, remember that only point positions can change, not the number of points
  60338. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60339. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60340. * @param name defines the name of the new line system
  60341. * @param options defines the options used to create the line system
  60342. * @param scene defines the hosting scene
  60343. * @returns a new line mesh
  60344. */
  60345. MeshBuilder.CreateLines = function (name, options, scene) {
  60346. if (scene === void 0) { scene = null; }
  60347. var colors = (options.colors) ? [options.colors] : null;
  60348. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60349. return lines;
  60350. };
  60351. /**
  60352. * Creates a dashed line mesh
  60353. * * 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
  60354. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60355. * * The parameter `points` is an array successive Vector3
  60356. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60357. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60358. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60359. * * 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
  60360. * * When updating an instance, remember that only point positions can change, not the number of points
  60361. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60362. * @param name defines the name of the mesh
  60363. * @param options defines the options used to create the mesh
  60364. * @param scene defines the hosting scene
  60365. * @returns the dashed line mesh
  60366. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60367. */
  60368. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60369. if (scene === void 0) { scene = null; }
  60370. var points = options.points;
  60371. var instance = options.instance;
  60372. var gapSize = options.gapSize || 1;
  60373. var dashSize = options.dashSize || 3;
  60374. if (instance) { // dashed lines update
  60375. var positionFunction = function (positions) {
  60376. var curvect = BABYLON.Vector3.Zero();
  60377. var nbSeg = positions.length / 6;
  60378. var lg = 0;
  60379. var nb = 0;
  60380. var shft = 0;
  60381. var dashshft = 0;
  60382. var curshft = 0;
  60383. var p = 0;
  60384. var i = 0;
  60385. var j = 0;
  60386. for (i = 0; i < points.length - 1; i++) {
  60387. points[i + 1].subtractToRef(points[i], curvect);
  60388. lg += curvect.length();
  60389. }
  60390. shft = lg / nbSeg;
  60391. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60392. for (i = 0; i < points.length - 1; i++) {
  60393. points[i + 1].subtractToRef(points[i], curvect);
  60394. nb = Math.floor(curvect.length() / shft);
  60395. curvect.normalize();
  60396. j = 0;
  60397. while (j < nb && p < positions.length) {
  60398. curshft = shft * j;
  60399. positions[p] = points[i].x + curshft * curvect.x;
  60400. positions[p + 1] = points[i].y + curshft * curvect.y;
  60401. positions[p + 2] = points[i].z + curshft * curvect.z;
  60402. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60403. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60404. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60405. p += 6;
  60406. j++;
  60407. }
  60408. }
  60409. while (p < positions.length) {
  60410. positions[p] = points[i].x;
  60411. positions[p + 1] = points[i].y;
  60412. positions[p + 2] = points[i].z;
  60413. p += 3;
  60414. }
  60415. };
  60416. instance.updateMeshPositions(positionFunction, false);
  60417. return instance;
  60418. }
  60419. // dashed lines creation
  60420. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60421. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60422. vertexData.applyToMesh(dashedLines, options.updatable);
  60423. dashedLines.dashSize = dashSize;
  60424. dashedLines.gapSize = gapSize;
  60425. return dashedLines;
  60426. };
  60427. /**
  60428. * 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.
  60429. * * 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.
  60430. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60431. * * 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.
  60432. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60433. * * 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
  60434. * * 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
  60435. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60436. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60437. * * 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
  60438. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60439. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60440. * @param name defines the name of the mesh
  60441. * @param options defines the options used to create the mesh
  60442. * @param scene defines the hosting scene
  60443. * @returns the extruded shape mesh
  60444. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60445. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60446. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60447. */
  60448. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60449. if (scene === void 0) { scene = null; }
  60450. var path = options.path;
  60451. var shape = options.shape;
  60452. var scale = options.scale || 1;
  60453. var rotation = options.rotation || 0;
  60454. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60455. var updatable = options.updatable;
  60456. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60457. var instance = options.instance || null;
  60458. var invertUV = options.invertUV || false;
  60459. 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);
  60460. };
  60461. /**
  60462. * Creates an custom extruded shape mesh.
  60463. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60464. * * 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.
  60465. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60466. * * 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
  60467. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60468. * * 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
  60469. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60470. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60471. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60472. * * 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
  60473. * * 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
  60474. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60475. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60476. * * 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
  60477. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60478. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60479. * @param name defines the name of the mesh
  60480. * @param options defines the options used to create the mesh
  60481. * @param scene defines the hosting scene
  60482. * @returns the custom extruded shape mesh
  60483. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60484. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60485. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60486. */
  60487. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60488. var path = options.path;
  60489. var shape = options.shape;
  60490. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60491. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60492. var ribbonCloseArray = options.ribbonCloseArray || false;
  60493. var ribbonClosePath = options.ribbonClosePath || false;
  60494. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60495. var updatable = options.updatable;
  60496. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60497. var instance = options.instance;
  60498. var invertUV = options.invertUV || false;
  60499. 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);
  60500. };
  60501. /**
  60502. * Creates lathe mesh.
  60503. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60504. * * 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
  60505. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60506. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60507. * * 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
  60508. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60509. * * 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
  60510. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60511. * * 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
  60512. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60513. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60514. * @param name defines the name of the mesh
  60515. * @param options defines the options used to create the mesh
  60516. * @param scene defines the hosting scene
  60517. * @returns the lathe mesh
  60518. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60519. */
  60520. MeshBuilder.CreateLathe = function (name, options, scene) {
  60521. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60522. var closed = (options.closed === undefined) ? true : options.closed;
  60523. var shape = options.shape;
  60524. var radius = options.radius || 1;
  60525. var tessellation = options.tessellation || 64;
  60526. var updatable = options.updatable;
  60527. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60528. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60529. var pi2 = Math.PI * 2;
  60530. var paths = new Array();
  60531. var invertUV = options.invertUV || false;
  60532. var i = 0;
  60533. var p = 0;
  60534. var step = pi2 / tessellation * arc;
  60535. var rotated;
  60536. var path = new Array();
  60537. ;
  60538. for (i = 0; i <= tessellation; i++) {
  60539. var path = [];
  60540. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60541. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60542. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60543. }
  60544. for (p = 0; p < shape.length; p++) {
  60545. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60546. path.push(rotated);
  60547. }
  60548. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60549. 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));
  60550. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60551. }
  60552. paths.push(path);
  60553. }
  60554. // lathe ribbon
  60555. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60556. return lathe;
  60557. };
  60558. /**
  60559. * Creates a plane mesh
  60560. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60561. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60562. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60563. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60564. * * 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
  60565. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60566. * @param name defines the name of the mesh
  60567. * @param options defines the options used to create the mesh
  60568. * @param scene defines the hosting scene
  60569. * @returns the plane mesh
  60570. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60571. */
  60572. MeshBuilder.CreatePlane = function (name, options, scene) {
  60573. var plane = new BABYLON.Mesh(name, scene);
  60574. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60575. plane._originalBuilderSideOrientation = options.sideOrientation;
  60576. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60577. vertexData.applyToMesh(plane, options.updatable);
  60578. if (options.sourcePlane) {
  60579. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60580. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60581. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60582. plane.rotate(vectorProduct, product);
  60583. }
  60584. return plane;
  60585. };
  60586. /**
  60587. * Creates a ground mesh
  60588. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60589. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60590. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60591. * @param name defines the name of the mesh
  60592. * @param options defines the options used to create the mesh
  60593. * @param scene defines the hosting scene
  60594. * @returns the ground mesh
  60595. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60596. */
  60597. MeshBuilder.CreateGround = function (name, options, scene) {
  60598. var ground = new BABYLON.GroundMesh(name, scene);
  60599. ground._setReady(false);
  60600. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60601. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60602. ground._width = options.width || 1;
  60603. ground._height = options.height || 1;
  60604. ground._maxX = ground._width / 2;
  60605. ground._maxZ = ground._height / 2;
  60606. ground._minX = -ground._maxX;
  60607. ground._minZ = -ground._maxZ;
  60608. var vertexData = BABYLON.VertexData.CreateGround(options);
  60609. vertexData.applyToMesh(ground, options.updatable);
  60610. ground._setReady(true);
  60611. return ground;
  60612. };
  60613. /**
  60614. * Creates a tiled ground mesh
  60615. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60616. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60617. * * 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
  60618. * * 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
  60619. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60620. * @param name defines the name of the mesh
  60621. * @param options defines the options used to create the mesh
  60622. * @param scene defines the hosting scene
  60623. * @returns the tiled ground mesh
  60624. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60625. */
  60626. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60627. var tiledGround = new BABYLON.Mesh(name, scene);
  60628. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60629. vertexData.applyToMesh(tiledGround, options.updatable);
  60630. return tiledGround;
  60631. };
  60632. /**
  60633. * Creates a ground mesh from a height map
  60634. * * The parameter `url` sets the URL of the height map image resource.
  60635. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60636. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60637. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60638. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60639. * * 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.
  60640. * * 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).
  60641. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60642. * @param name defines the name of the mesh
  60643. * @param url defines the url to the height map
  60644. * @param options defines the options used to create the mesh
  60645. * @param scene defines the hosting scene
  60646. * @returns the ground mesh
  60647. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60648. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60649. */
  60650. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60651. var width = options.width || 10.0;
  60652. var height = options.height || 10.0;
  60653. var subdivisions = options.subdivisions || 1 | 0;
  60654. var minHeight = options.minHeight || 0.0;
  60655. var maxHeight = options.maxHeight || 1.0;
  60656. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60657. var updatable = options.updatable;
  60658. var onReady = options.onReady;
  60659. var ground = new BABYLON.GroundMesh(name, scene);
  60660. ground._subdivisionsX = subdivisions;
  60661. ground._subdivisionsY = subdivisions;
  60662. ground._width = width;
  60663. ground._height = height;
  60664. ground._maxX = ground._width / 2.0;
  60665. ground._maxZ = ground._height / 2.0;
  60666. ground._minX = -ground._maxX;
  60667. ground._minZ = -ground._maxZ;
  60668. ground._setReady(false);
  60669. var onload = function (img) {
  60670. // Getting height map data
  60671. var canvas = document.createElement("canvas");
  60672. var context = canvas.getContext("2d");
  60673. if (!context) {
  60674. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60675. }
  60676. if (scene.isDisposed) {
  60677. return;
  60678. }
  60679. var bufferWidth = img.width;
  60680. var bufferHeight = img.height;
  60681. canvas.width = bufferWidth;
  60682. canvas.height = bufferHeight;
  60683. context.drawImage(img, 0, 0);
  60684. // Create VertexData from map data
  60685. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60686. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60687. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60688. width: width, height: height,
  60689. subdivisions: subdivisions,
  60690. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60691. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60692. });
  60693. vertexData.applyToMesh(ground, updatable);
  60694. //execute ready callback, if set
  60695. if (onReady) {
  60696. onReady(ground);
  60697. }
  60698. ground._setReady(true);
  60699. };
  60700. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60701. return ground;
  60702. };
  60703. /**
  60704. * Creates a polygon mesh
  60705. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60706. * * 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
  60707. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60708. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60709. * * 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)
  60710. * * Remember you can only change the shape positions, not their number when updating a polygon
  60711. * @param name defines the name of the mesh
  60712. * @param options defines the options used to create the mesh
  60713. * @param scene defines the hosting scene
  60714. * @returns the polygon mesh
  60715. */
  60716. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60717. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60718. var shape = options.shape;
  60719. var holes = options.holes || [];
  60720. var depth = options.depth || 0;
  60721. var contours = [];
  60722. var hole = [];
  60723. for (var i = 0; i < shape.length; i++) {
  60724. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60725. }
  60726. var epsilon = 0.00000001;
  60727. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60728. contours.pop();
  60729. }
  60730. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60731. for (var hNb = 0; hNb < holes.length; hNb++) {
  60732. hole = [];
  60733. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60734. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60735. }
  60736. polygonTriangulation.addHole(hole);
  60737. }
  60738. var polygon = polygonTriangulation.build(options.updatable, depth);
  60739. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60740. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60741. vertexData.applyToMesh(polygon, options.updatable);
  60742. return polygon;
  60743. };
  60744. ;
  60745. /**
  60746. * Creates an extruded polygon mesh, with depth in the Y direction.
  60747. * * 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)
  60748. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60749. * @param name defines the name of the mesh
  60750. * @param options defines the options used to create the mesh
  60751. * @param scene defines the hosting scene
  60752. * @returns the polygon mesh
  60753. */
  60754. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60755. return MeshBuilder.CreatePolygon(name, options, scene);
  60756. };
  60757. ;
  60758. /**
  60759. * Creates a tube mesh.
  60760. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60761. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60762. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60763. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60764. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60765. * * 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)
  60766. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60767. * * 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
  60768. * * 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
  60769. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60770. * * 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
  60771. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60773. * @param name defines the name of the mesh
  60774. * @param options defines the options used to create the mesh
  60775. * @param scene defines the hosting scene
  60776. * @returns the tube mesh
  60777. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60778. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60779. */
  60780. MeshBuilder.CreateTube = function (name, options, scene) {
  60781. var path = options.path;
  60782. var instance = options.instance;
  60783. var radius = 1.0;
  60784. if (instance) {
  60785. radius = instance.radius;
  60786. }
  60787. if (options.radius !== undefined) {
  60788. radius = options.radius;
  60789. }
  60790. ;
  60791. var tessellation = options.tessellation || 64 | 0;
  60792. var radiusFunction = options.radiusFunction || null;
  60793. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60794. var invertUV = options.invertUV || false;
  60795. var updatable = options.updatable;
  60796. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60797. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60798. // tube geometry
  60799. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60800. var tangents = path3D.getTangents();
  60801. var normals = path3D.getNormals();
  60802. var distances = path3D.getDistances();
  60803. var pi2 = Math.PI * 2;
  60804. var step = pi2 / tessellation * arc;
  60805. var returnRadius = function () { return radius; };
  60806. var radiusFunctionFinal = radiusFunction || returnRadius;
  60807. var circlePath;
  60808. var rad;
  60809. var normal;
  60810. var rotated;
  60811. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60812. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60813. for (var i = 0; i < path.length; i++) {
  60814. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60815. circlePath = Array(); // current circle array
  60816. normal = normals[i]; // current normal
  60817. for (var t = 0; t < tessellation; t++) {
  60818. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60819. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60820. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60821. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60822. circlePath[t] = rotated;
  60823. }
  60824. circlePaths[index] = circlePath;
  60825. index++;
  60826. }
  60827. // cap
  60828. var capPath = function (nbPoints, pathIndex) {
  60829. var pointCap = Array();
  60830. for (var i = 0; i < nbPoints; i++) {
  60831. pointCap.push(path[pathIndex]);
  60832. }
  60833. return pointCap;
  60834. };
  60835. switch (cap) {
  60836. case BABYLON.Mesh.NO_CAP:
  60837. break;
  60838. case BABYLON.Mesh.CAP_START:
  60839. circlePaths[0] = capPath(tessellation, 0);
  60840. circlePaths[1] = circlePaths[2].slice(0);
  60841. break;
  60842. case BABYLON.Mesh.CAP_END:
  60843. circlePaths[index] = circlePaths[index - 1].slice(0);
  60844. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60845. break;
  60846. case BABYLON.Mesh.CAP_ALL:
  60847. circlePaths[0] = capPath(tessellation, 0);
  60848. circlePaths[1] = circlePaths[2].slice(0);
  60849. circlePaths[index] = circlePaths[index - 1].slice(0);
  60850. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60851. break;
  60852. default:
  60853. break;
  60854. }
  60855. return circlePaths;
  60856. };
  60857. var path3D;
  60858. var pathArray;
  60859. if (instance) { // tube update
  60860. var arc = options.arc || instance.arc;
  60861. path3D = (instance.path3D).update(path);
  60862. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60863. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60864. instance.path3D = path3D;
  60865. instance.pathArray = pathArray;
  60866. instance.arc = arc;
  60867. instance.radius = radius;
  60868. return instance;
  60869. }
  60870. // tube creation
  60871. path3D = new BABYLON.Path3D(path);
  60872. var newPathArray = new Array();
  60873. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60874. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60875. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60876. tube.pathArray = pathArray;
  60877. tube.path3D = path3D;
  60878. tube.tessellation = tessellation;
  60879. tube.cap = cap;
  60880. tube.arc = options.arc;
  60881. tube.radius = radius;
  60882. return tube;
  60883. };
  60884. /**
  60885. * Creates a polyhedron mesh
  60886. * * 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
  60887. * * The parameter `size` (positive float, default 1) sets the polygon size
  60888. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60889. * * 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`
  60890. * * 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
  60891. * * 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)`)
  60892. * * 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
  60893. * * 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
  60894. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60895. * * 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
  60896. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60897. * @param name defines the name of the mesh
  60898. * @param options defines the options used to create the mesh
  60899. * @param scene defines the hosting scene
  60900. * @returns the polyhedron mesh
  60901. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60902. */
  60903. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60904. var polyhedron = new BABYLON.Mesh(name, scene);
  60905. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60906. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60907. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60908. vertexData.applyToMesh(polyhedron, options.updatable);
  60909. return polyhedron;
  60910. };
  60911. /**
  60912. * Creates a decal mesh.
  60913. * 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
  60914. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60915. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60916. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60917. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60918. * @param name defines the name of the mesh
  60919. * @param sourceMesh defines the mesh where the decal must be applied
  60920. * @param options defines the options used to create the mesh
  60921. * @param scene defines the hosting scene
  60922. * @returns the decal mesh
  60923. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60924. */
  60925. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60926. var indices = sourceMesh.getIndices();
  60927. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60928. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60929. var position = options.position || BABYLON.Vector3.Zero();
  60930. var normal = options.normal || BABYLON.Vector3.Up();
  60931. var size = options.size || BABYLON.Vector3.One();
  60932. var angle = options.angle || 0;
  60933. // Getting correct rotation
  60934. if (!normal) {
  60935. var target = new BABYLON.Vector3(0, 0, 1);
  60936. var camera = sourceMesh.getScene().activeCamera;
  60937. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60938. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60939. }
  60940. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  60941. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  60942. var pitch = Math.atan2(normal.y, len);
  60943. // Matrix
  60944. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  60945. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  60946. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  60947. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  60948. var vertexData = new BABYLON.VertexData();
  60949. vertexData.indices = [];
  60950. vertexData.positions = [];
  60951. vertexData.normals = [];
  60952. vertexData.uvs = [];
  60953. var currentVertexDataIndex = 0;
  60954. var extractDecalVector3 = function (indexId) {
  60955. var result = new BABYLON.PositionNormalVertex();
  60956. if (!indices || !positions || !normals) {
  60957. return result;
  60958. }
  60959. var vertexId = indices[indexId];
  60960. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  60961. // Send vector to decal local world
  60962. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  60963. // Get normal
  60964. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  60965. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  60966. return result;
  60967. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  60968. var clip = function (vertices, axis) {
  60969. if (vertices.length === 0) {
  60970. return vertices;
  60971. }
  60972. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  60973. var clipVertices = function (v0, v1) {
  60974. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  60975. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  60976. };
  60977. var result = new Array();
  60978. for (var index = 0; index < vertices.length; index += 3) {
  60979. var v1Out;
  60980. var v2Out;
  60981. var v3Out;
  60982. var total = 0;
  60983. var nV1 = null;
  60984. var nV2 = null;
  60985. var nV3 = null;
  60986. var nV4 = null;
  60987. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  60988. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  60989. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  60990. v1Out = d1 > 0;
  60991. v2Out = d2 > 0;
  60992. v3Out = d3 > 0;
  60993. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  60994. switch (total) {
  60995. case 0:
  60996. result.push(vertices[index]);
  60997. result.push(vertices[index + 1]);
  60998. result.push(vertices[index + 2]);
  60999. break;
  61000. case 1:
  61001. if (v1Out) {
  61002. nV1 = vertices[index + 1];
  61003. nV2 = vertices[index + 2];
  61004. nV3 = clipVertices(vertices[index], nV1);
  61005. nV4 = clipVertices(vertices[index], nV2);
  61006. }
  61007. if (v2Out) {
  61008. nV1 = vertices[index];
  61009. nV2 = vertices[index + 2];
  61010. nV3 = clipVertices(vertices[index + 1], nV1);
  61011. nV4 = clipVertices(vertices[index + 1], nV2);
  61012. result.push(nV3);
  61013. result.push(nV2.clone());
  61014. result.push(nV1.clone());
  61015. result.push(nV2.clone());
  61016. result.push(nV3.clone());
  61017. result.push(nV4);
  61018. break;
  61019. }
  61020. if (v3Out) {
  61021. nV1 = vertices[index];
  61022. nV2 = vertices[index + 1];
  61023. nV3 = clipVertices(vertices[index + 2], nV1);
  61024. nV4 = clipVertices(vertices[index + 2], nV2);
  61025. }
  61026. if (nV1 && nV2 && nV3 && nV4) {
  61027. result.push(nV1.clone());
  61028. result.push(nV2.clone());
  61029. result.push(nV3);
  61030. result.push(nV4);
  61031. result.push(nV3.clone());
  61032. result.push(nV2.clone());
  61033. }
  61034. break;
  61035. case 2:
  61036. if (!v1Out) {
  61037. nV1 = vertices[index].clone();
  61038. nV2 = clipVertices(nV1, vertices[index + 1]);
  61039. nV3 = clipVertices(nV1, vertices[index + 2]);
  61040. result.push(nV1);
  61041. result.push(nV2);
  61042. result.push(nV3);
  61043. }
  61044. if (!v2Out) {
  61045. nV1 = vertices[index + 1].clone();
  61046. nV2 = clipVertices(nV1, vertices[index + 2]);
  61047. nV3 = clipVertices(nV1, vertices[index]);
  61048. result.push(nV1);
  61049. result.push(nV2);
  61050. result.push(nV3);
  61051. }
  61052. if (!v3Out) {
  61053. nV1 = vertices[index + 2].clone();
  61054. nV2 = clipVertices(nV1, vertices[index]);
  61055. nV3 = clipVertices(nV1, vertices[index + 1]);
  61056. result.push(nV1);
  61057. result.push(nV2);
  61058. result.push(nV3);
  61059. }
  61060. break;
  61061. case 3:
  61062. break;
  61063. }
  61064. }
  61065. return result;
  61066. };
  61067. for (var index = 0; index < indices.length; index += 3) {
  61068. var faceVertices = new Array();
  61069. faceVertices.push(extractDecalVector3(index));
  61070. faceVertices.push(extractDecalVector3(index + 1));
  61071. faceVertices.push(extractDecalVector3(index + 2));
  61072. // Clip
  61073. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61074. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61075. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61076. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61077. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61078. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61079. if (faceVertices.length === 0) {
  61080. continue;
  61081. }
  61082. // Add UVs and get back to world
  61083. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61084. var vertex = faceVertices[vIndex];
  61085. //TODO check for Int32Array | Uint32Array | Uint16Array
  61086. vertexData.indices.push(currentVertexDataIndex);
  61087. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61088. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61089. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61090. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61091. currentVertexDataIndex++;
  61092. }
  61093. }
  61094. // Return mesh
  61095. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61096. vertexData.applyToMesh(decal);
  61097. decal.position = position.clone();
  61098. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61099. return decal;
  61100. };
  61101. // Privates
  61102. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61103. // extrusion geometry
  61104. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61105. var tangents = path3D.getTangents();
  61106. var normals = path3D.getNormals();
  61107. var binormals = path3D.getBinormals();
  61108. var distances = path3D.getDistances();
  61109. var angle = 0;
  61110. var returnScale = function () { return scale !== null ? scale : 1; };
  61111. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61112. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61113. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61114. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61115. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61116. for (var i = 0; i < curve.length; i++) {
  61117. var shapePath = new Array();
  61118. var angleStep = rotate(i, distances[i]);
  61119. var scaleRatio = scl(i, distances[i]);
  61120. for (var p = 0; p < shape.length; p++) {
  61121. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61122. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61123. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61124. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61125. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61126. shapePath[p] = rotated;
  61127. }
  61128. shapePaths[index] = shapePath;
  61129. angle += angleStep;
  61130. index++;
  61131. }
  61132. // cap
  61133. var capPath = function (shapePath) {
  61134. var pointCap = Array();
  61135. var barycenter = BABYLON.Vector3.Zero();
  61136. var i;
  61137. for (i = 0; i < shapePath.length; i++) {
  61138. barycenter.addInPlace(shapePath[i]);
  61139. }
  61140. barycenter.scaleInPlace(1.0 / shapePath.length);
  61141. for (i = 0; i < shapePath.length; i++) {
  61142. pointCap.push(barycenter);
  61143. }
  61144. return pointCap;
  61145. };
  61146. switch (cap) {
  61147. case BABYLON.Mesh.NO_CAP:
  61148. break;
  61149. case BABYLON.Mesh.CAP_START:
  61150. shapePaths[0] = capPath(shapePaths[2]);
  61151. shapePaths[1] = shapePaths[2];
  61152. break;
  61153. case BABYLON.Mesh.CAP_END:
  61154. shapePaths[index] = shapePaths[index - 1];
  61155. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61156. break;
  61157. case BABYLON.Mesh.CAP_ALL:
  61158. shapePaths[0] = capPath(shapePaths[2]);
  61159. shapePaths[1] = shapePaths[2];
  61160. shapePaths[index] = shapePaths[index - 1];
  61161. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61162. break;
  61163. default:
  61164. break;
  61165. }
  61166. return shapePaths;
  61167. };
  61168. var path3D;
  61169. var pathArray;
  61170. if (instance) { // instance update
  61171. path3D = (instance.path3D).update(curve);
  61172. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61173. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61174. return instance;
  61175. }
  61176. // extruded shape creation
  61177. path3D = new BABYLON.Path3D(curve);
  61178. var newShapePaths = new Array();
  61179. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61180. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61181. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61182. extrudedGeneric.pathArray = pathArray;
  61183. extrudedGeneric.path3D = path3D;
  61184. extrudedGeneric.cap = cap;
  61185. return extrudedGeneric;
  61186. };
  61187. return MeshBuilder;
  61188. }());
  61189. BABYLON.MeshBuilder = MeshBuilder;
  61190. })(BABYLON || (BABYLON = {}));
  61191. //# sourceMappingURL=babylon.meshBuilder.js.map
  61192. var BABYLON;
  61193. (function (BABYLON) {
  61194. /**
  61195. * Draco compression (https://google.github.io/draco/)
  61196. */
  61197. var DracoCompression = /** @class */ (function () {
  61198. /**
  61199. * Constructor
  61200. */
  61201. function DracoCompression() {
  61202. }
  61203. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61204. /**
  61205. * Returns true if the decoder is available.
  61206. */
  61207. get: function () {
  61208. if (typeof DracoDecoderModule !== "undefined") {
  61209. return true;
  61210. }
  61211. var decoder = DracoCompression.Configuration.decoder;
  61212. if (decoder) {
  61213. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61214. return true;
  61215. }
  61216. if (decoder.fallbackUrl) {
  61217. return true;
  61218. }
  61219. }
  61220. return false;
  61221. },
  61222. enumerable: true,
  61223. configurable: true
  61224. });
  61225. /**
  61226. * Stop all async operations and release resources.
  61227. */
  61228. DracoCompression.prototype.dispose = function () {
  61229. };
  61230. /**
  61231. * Decode Draco compressed mesh data to vertex data.
  61232. * @param data The array buffer view for the Draco compression data
  61233. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61234. * @returns A promise that resolves with the decoded vertex data
  61235. */
  61236. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61237. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61238. var module = wrappedModule.module;
  61239. var vertexData = new BABYLON.VertexData();
  61240. var buffer = new module.DecoderBuffer();
  61241. buffer.Init(data, data.byteLength);
  61242. var decoder = new module.Decoder();
  61243. var geometry;
  61244. var status;
  61245. try {
  61246. var type = decoder.GetEncodedGeometryType(buffer);
  61247. switch (type) {
  61248. case module.TRIANGULAR_MESH:
  61249. geometry = new module.Mesh();
  61250. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61251. break;
  61252. case module.POINT_CLOUD:
  61253. geometry = new module.PointCloud();
  61254. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61255. break;
  61256. default:
  61257. throw new Error("Invalid geometry type " + type);
  61258. }
  61259. if (!status.ok() || !geometry.ptr) {
  61260. throw new Error(status.error_msg());
  61261. }
  61262. var numPoints = geometry.num_points();
  61263. if (type === module.TRIANGULAR_MESH) {
  61264. var numFaces = geometry.num_faces();
  61265. var faceIndices = new module.DracoInt32Array();
  61266. try {
  61267. var indices = new Uint32Array(numFaces * 3);
  61268. for (var i = 0; i < numFaces; i++) {
  61269. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61270. var offset = i * 3;
  61271. indices[offset + 0] = faceIndices.GetValue(0);
  61272. indices[offset + 1] = faceIndices.GetValue(1);
  61273. indices[offset + 2] = faceIndices.GetValue(2);
  61274. }
  61275. vertexData.indices = indices;
  61276. }
  61277. finally {
  61278. module.destroy(faceIndices);
  61279. }
  61280. }
  61281. for (var kind in attributes) {
  61282. var uniqueId = attributes[kind];
  61283. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61284. var dracoData = new module.DracoFloat32Array();
  61285. try {
  61286. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61287. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61288. for (var i = 0; i < babylonData.length; i++) {
  61289. babylonData[i] = dracoData.GetValue(i);
  61290. }
  61291. vertexData.set(babylonData, kind);
  61292. }
  61293. finally {
  61294. module.destroy(dracoData);
  61295. }
  61296. }
  61297. }
  61298. finally {
  61299. if (geometry) {
  61300. module.destroy(geometry);
  61301. }
  61302. module.destroy(decoder);
  61303. module.destroy(buffer);
  61304. }
  61305. return vertexData;
  61306. });
  61307. };
  61308. DracoCompression._GetDecoderModule = function () {
  61309. if (!DracoCompression._DecoderModulePromise) {
  61310. var promise = null;
  61311. var config_1 = {};
  61312. if (typeof DracoDecoderModule !== "undefined") {
  61313. promise = Promise.resolve();
  61314. }
  61315. else {
  61316. var decoder = DracoCompression.Configuration.decoder;
  61317. if (decoder) {
  61318. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61319. promise = Promise.all([
  61320. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61321. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61322. config_1.wasmBinary = data;
  61323. })
  61324. ]);
  61325. }
  61326. else if (decoder.fallbackUrl) {
  61327. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61328. }
  61329. }
  61330. }
  61331. if (!promise) {
  61332. throw new Error("Draco decoder module is not available");
  61333. }
  61334. DracoCompression._DecoderModulePromise = promise.then(function () {
  61335. return new Promise(function (resolve) {
  61336. config_1.onModuleLoaded = function (decoderModule) {
  61337. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61338. resolve({ module: decoderModule });
  61339. };
  61340. DracoDecoderModule(config_1);
  61341. });
  61342. });
  61343. }
  61344. return DracoCompression._DecoderModulePromise;
  61345. };
  61346. DracoCompression._LoadScriptAsync = function (url) {
  61347. return new Promise(function (resolve, reject) {
  61348. BABYLON.Tools.LoadScript(url, function () {
  61349. resolve();
  61350. }, function (message) {
  61351. reject(new Error(message));
  61352. });
  61353. });
  61354. };
  61355. DracoCompression._LoadFileAsync = function (url) {
  61356. return new Promise(function (resolve, reject) {
  61357. BABYLON.Tools.LoadFile(url, function (data) {
  61358. resolve(data);
  61359. }, undefined, undefined, true, function (request, exception) {
  61360. reject(exception);
  61361. });
  61362. });
  61363. };
  61364. /**
  61365. * The configuration.
  61366. */
  61367. DracoCompression.Configuration = {
  61368. decoder: {
  61369. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61370. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61371. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61372. }
  61373. };
  61374. return DracoCompression;
  61375. }());
  61376. BABYLON.DracoCompression = DracoCompression;
  61377. })(BABYLON || (BABYLON = {}));
  61378. //# sourceMappingURL=babylon.dracoCompression.js.map
  61379. var BABYLON;
  61380. (function (BABYLON) {
  61381. var AudioEngine = /** @class */ (function () {
  61382. function AudioEngine() {
  61383. this._audioContext = null;
  61384. this._audioContextInitialized = false;
  61385. this.canUseWebAudio = false;
  61386. this.WarnedWebAudioUnsupported = false;
  61387. this.unlocked = false;
  61388. this.isMP3supported = false;
  61389. this.isOGGsupported = false;
  61390. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61391. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61392. this.canUseWebAudio = true;
  61393. }
  61394. var audioElem = document.createElement('audio');
  61395. try {
  61396. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61397. this.isMP3supported = true;
  61398. }
  61399. }
  61400. catch (e) {
  61401. // protect error during capability check.
  61402. }
  61403. try {
  61404. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61405. this.isOGGsupported = true;
  61406. }
  61407. }
  61408. catch (e) {
  61409. // protect error during capability check.
  61410. }
  61411. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61412. this._unlockiOSaudio();
  61413. }
  61414. else {
  61415. this.unlocked = true;
  61416. }
  61417. }
  61418. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61419. get: function () {
  61420. if (!this._audioContextInitialized) {
  61421. this._initializeAudioContext();
  61422. }
  61423. return this._audioContext;
  61424. },
  61425. enumerable: true,
  61426. configurable: true
  61427. });
  61428. AudioEngine.prototype._unlockiOSaudio = function () {
  61429. var _this = this;
  61430. var unlockaudio = function () {
  61431. if (!_this.audioContext) {
  61432. return;
  61433. }
  61434. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61435. var source = _this.audioContext.createBufferSource();
  61436. source.buffer = buffer;
  61437. source.connect(_this.audioContext.destination);
  61438. source.start(0);
  61439. setTimeout(function () {
  61440. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61441. _this.unlocked = true;
  61442. window.removeEventListener('touchend', unlockaudio, false);
  61443. if (_this.onAudioUnlocked) {
  61444. _this.onAudioUnlocked();
  61445. }
  61446. }
  61447. }, 0);
  61448. };
  61449. window.addEventListener('touchend', unlockaudio, false);
  61450. };
  61451. AudioEngine.prototype._initializeAudioContext = function () {
  61452. try {
  61453. if (this.canUseWebAudio) {
  61454. this._audioContext = new AudioContext();
  61455. // create a global volume gain node
  61456. this.masterGain = this._audioContext.createGain();
  61457. this.masterGain.gain.value = 1;
  61458. this.masterGain.connect(this._audioContext.destination);
  61459. this._audioContextInitialized = true;
  61460. }
  61461. }
  61462. catch (e) {
  61463. this.canUseWebAudio = false;
  61464. BABYLON.Tools.Error("Web Audio: " + e.message);
  61465. }
  61466. };
  61467. AudioEngine.prototype.dispose = function () {
  61468. if (this.canUseWebAudio && this._audioContextInitialized) {
  61469. if (this._connectedAnalyser && this._audioContext) {
  61470. this._connectedAnalyser.stopDebugCanvas();
  61471. this._connectedAnalyser.dispose();
  61472. this.masterGain.disconnect();
  61473. this.masterGain.connect(this._audioContext.destination);
  61474. this._connectedAnalyser = null;
  61475. }
  61476. this.masterGain.gain.value = 1;
  61477. }
  61478. this.WarnedWebAudioUnsupported = false;
  61479. };
  61480. AudioEngine.prototype.getGlobalVolume = function () {
  61481. if (this.canUseWebAudio && this._audioContextInitialized) {
  61482. return this.masterGain.gain.value;
  61483. }
  61484. else {
  61485. return -1;
  61486. }
  61487. };
  61488. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61489. if (this.canUseWebAudio && this._audioContextInitialized) {
  61490. this.masterGain.gain.value = newVolume;
  61491. }
  61492. };
  61493. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61494. if (this._connectedAnalyser) {
  61495. this._connectedAnalyser.stopDebugCanvas();
  61496. }
  61497. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61498. this._connectedAnalyser = analyser;
  61499. this.masterGain.disconnect();
  61500. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61501. }
  61502. };
  61503. return AudioEngine;
  61504. }());
  61505. BABYLON.AudioEngine = AudioEngine;
  61506. })(BABYLON || (BABYLON = {}));
  61507. //# sourceMappingURL=babylon.audioEngine.js.map
  61508. var BABYLON;
  61509. (function (BABYLON) {
  61510. var Sound = /** @class */ (function () {
  61511. /**
  61512. * Create a sound and attach it to a scene
  61513. * @param name Name of your sound
  61514. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61515. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61516. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61517. */
  61518. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61519. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61520. var _this = this;
  61521. this.autoplay = false;
  61522. this.loop = false;
  61523. this.useCustomAttenuation = false;
  61524. this.spatialSound = false;
  61525. this.refDistance = 1;
  61526. this.rolloffFactor = 1;
  61527. this.maxDistance = 100;
  61528. this.distanceModel = "linear";
  61529. this._panningModel = "equalpower";
  61530. this._playbackRate = 1;
  61531. this._streaming = false;
  61532. this._startTime = 0;
  61533. this._startOffset = 0;
  61534. this._position = BABYLON.Vector3.Zero();
  61535. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61536. this._volume = 1;
  61537. this._isReadyToPlay = false;
  61538. this.isPlaying = false;
  61539. this.isPaused = false;
  61540. this._isDirectional = false;
  61541. // Used if you'd like to create a directional sound.
  61542. // If not set, the sound will be omnidirectional
  61543. this._coneInnerAngle = 360;
  61544. this._coneOuterAngle = 360;
  61545. this._coneOuterGain = 0;
  61546. this._isOutputConnected = false;
  61547. this._urlType = "Unknown";
  61548. this.name = name;
  61549. this._scene = scene;
  61550. this._readyToPlayCallback = readyToPlayCallback;
  61551. // Default custom attenuation function is a linear attenuation
  61552. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61553. if (currentDistance < maxDistance) {
  61554. return currentVolume * (1 - currentDistance / maxDistance);
  61555. }
  61556. else {
  61557. return 0;
  61558. }
  61559. };
  61560. if (options) {
  61561. this.autoplay = options.autoplay || false;
  61562. this.loop = options.loop || false;
  61563. // if volume === 0, we need another way to check this option
  61564. if (options.volume !== undefined) {
  61565. this._volume = options.volume;
  61566. }
  61567. this.spatialSound = options.spatialSound || false;
  61568. this.maxDistance = options.maxDistance || 100;
  61569. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61570. this.rolloffFactor = options.rolloffFactor || 1;
  61571. this.refDistance = options.refDistance || 1;
  61572. this.distanceModel = options.distanceModel || "linear";
  61573. this._playbackRate = options.playbackRate || 1;
  61574. this._streaming = options.streaming || false;
  61575. }
  61576. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61577. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61578. this._soundGain.gain.value = this._volume;
  61579. this._inputAudioNode = this._soundGain;
  61580. this._ouputAudioNode = this._soundGain;
  61581. if (this.spatialSound) {
  61582. this._createSpatialParameters();
  61583. }
  61584. this._scene.mainSoundTrack.AddSound(this);
  61585. var validParameter = true;
  61586. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61587. if (urlOrArrayBuffer) {
  61588. try {
  61589. if (typeof (urlOrArrayBuffer) === "string")
  61590. this._urlType = "String";
  61591. if (Array.isArray(urlOrArrayBuffer))
  61592. this._urlType = "Array";
  61593. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61594. this._urlType = "ArrayBuffer";
  61595. var urls = [];
  61596. var codecSupportedFound = false;
  61597. switch (this._urlType) {
  61598. case "ArrayBuffer":
  61599. if (urlOrArrayBuffer.byteLength > 0) {
  61600. codecSupportedFound = true;
  61601. this._soundLoaded(urlOrArrayBuffer);
  61602. }
  61603. break;
  61604. case "String":
  61605. urls.push(urlOrArrayBuffer);
  61606. case "Array":
  61607. if (urls.length === 0)
  61608. urls = urlOrArrayBuffer;
  61609. // If we found a supported format, we load it immediately and stop the loop
  61610. for (var i = 0; i < urls.length; i++) {
  61611. var url = urls[i];
  61612. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61613. codecSupportedFound = true;
  61614. }
  61615. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61616. codecSupportedFound = true;
  61617. }
  61618. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61619. codecSupportedFound = true;
  61620. }
  61621. if (url.indexOf("blob:") !== -1) {
  61622. codecSupportedFound = true;
  61623. }
  61624. if (codecSupportedFound) {
  61625. // Loading sound using XHR2
  61626. if (!this._streaming) {
  61627. this._scene._loadFile(url, function (data) {
  61628. _this._soundLoaded(data);
  61629. }, undefined, true, true, function (exception) {
  61630. if (exception) {
  61631. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61632. }
  61633. BABYLON.Tools.Error("Sound creation aborted.");
  61634. _this._scene.mainSoundTrack.RemoveSound(_this);
  61635. });
  61636. }
  61637. // Streaming sound using HTML5 Audio tag
  61638. else {
  61639. this._htmlAudioElement = new Audio(url);
  61640. this._htmlAudioElement.controls = false;
  61641. this._htmlAudioElement.loop = this.loop;
  61642. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61643. this._htmlAudioElement.preload = "auto";
  61644. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61645. _this._isReadyToPlay = true;
  61646. if (_this.autoplay) {
  61647. _this.play();
  61648. }
  61649. if (_this._readyToPlayCallback) {
  61650. _this._readyToPlayCallback();
  61651. }
  61652. });
  61653. document.body.appendChild(this._htmlAudioElement);
  61654. }
  61655. break;
  61656. }
  61657. }
  61658. break;
  61659. default:
  61660. validParameter = false;
  61661. break;
  61662. }
  61663. if (!validParameter) {
  61664. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61665. }
  61666. else {
  61667. if (!codecSupportedFound) {
  61668. this._isReadyToPlay = true;
  61669. // Simulating a ready to play event to avoid breaking code path
  61670. if (this._readyToPlayCallback) {
  61671. window.setTimeout(function () {
  61672. if (_this._readyToPlayCallback) {
  61673. _this._readyToPlayCallback();
  61674. }
  61675. }, 1000);
  61676. }
  61677. }
  61678. }
  61679. }
  61680. catch (ex) {
  61681. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61682. this._scene.mainSoundTrack.RemoveSound(this);
  61683. }
  61684. }
  61685. }
  61686. else {
  61687. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61688. this._scene.mainSoundTrack.AddSound(this);
  61689. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61690. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61691. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61692. }
  61693. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61694. if (this._readyToPlayCallback) {
  61695. window.setTimeout(function () {
  61696. if (_this._readyToPlayCallback) {
  61697. _this._readyToPlayCallback();
  61698. }
  61699. }, 1000);
  61700. }
  61701. }
  61702. }
  61703. Sound.prototype.dispose = function () {
  61704. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61705. if (this.isPlaying) {
  61706. this.stop();
  61707. }
  61708. this._isReadyToPlay = false;
  61709. if (this.soundTrackId === -1) {
  61710. this._scene.mainSoundTrack.RemoveSound(this);
  61711. }
  61712. else {
  61713. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61714. }
  61715. if (this._soundGain) {
  61716. this._soundGain.disconnect();
  61717. this._soundGain = null;
  61718. }
  61719. if (this._soundPanner) {
  61720. this._soundPanner.disconnect();
  61721. this._soundPanner = null;
  61722. }
  61723. if (this._soundSource) {
  61724. this._soundSource.disconnect();
  61725. this._soundSource = null;
  61726. }
  61727. this._audioBuffer = null;
  61728. if (this._htmlAudioElement) {
  61729. this._htmlAudioElement.pause();
  61730. this._htmlAudioElement.src = "";
  61731. document.body.removeChild(this._htmlAudioElement);
  61732. }
  61733. if (this._connectedMesh && this._registerFunc) {
  61734. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61735. this._connectedMesh = null;
  61736. }
  61737. }
  61738. };
  61739. Sound.prototype.isReady = function () {
  61740. return this._isReadyToPlay;
  61741. };
  61742. Sound.prototype._soundLoaded = function (audioData) {
  61743. var _this = this;
  61744. if (!BABYLON.Engine.audioEngine.audioContext) {
  61745. return;
  61746. }
  61747. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61748. _this._audioBuffer = buffer;
  61749. _this._isReadyToPlay = true;
  61750. if (_this.autoplay) {
  61751. _this.play();
  61752. }
  61753. if (_this._readyToPlayCallback) {
  61754. _this._readyToPlayCallback();
  61755. }
  61756. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61757. };
  61758. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61759. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61760. this._audioBuffer = audioBuffer;
  61761. this._isReadyToPlay = true;
  61762. }
  61763. };
  61764. Sound.prototype.updateOptions = function (options) {
  61765. if (options) {
  61766. this.loop = options.loop || this.loop;
  61767. this.maxDistance = options.maxDistance || this.maxDistance;
  61768. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61769. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61770. this.refDistance = options.refDistance || this.refDistance;
  61771. this.distanceModel = options.distanceModel || this.distanceModel;
  61772. this._playbackRate = options.playbackRate || this._playbackRate;
  61773. this._updateSpatialParameters();
  61774. if (this.isPlaying) {
  61775. if (this._streaming) {
  61776. this._htmlAudioElement.playbackRate = this._playbackRate;
  61777. }
  61778. else {
  61779. if (this._soundSource) {
  61780. this._soundSource.playbackRate.value = this._playbackRate;
  61781. }
  61782. }
  61783. }
  61784. }
  61785. };
  61786. Sound.prototype._createSpatialParameters = function () {
  61787. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61788. if (this._scene.headphone) {
  61789. this._panningModel = "HRTF";
  61790. }
  61791. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61792. this._updateSpatialParameters();
  61793. this._soundPanner.connect(this._ouputAudioNode);
  61794. this._inputAudioNode = this._soundPanner;
  61795. }
  61796. };
  61797. Sound.prototype._updateSpatialParameters = function () {
  61798. if (this.spatialSound && this._soundPanner) {
  61799. if (this.useCustomAttenuation) {
  61800. // Tricks to disable in a way embedded Web Audio attenuation
  61801. this._soundPanner.distanceModel = "linear";
  61802. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61803. this._soundPanner.refDistance = 1;
  61804. this._soundPanner.rolloffFactor = 1;
  61805. this._soundPanner.panningModel = this._panningModel;
  61806. }
  61807. else {
  61808. this._soundPanner.distanceModel = this.distanceModel;
  61809. this._soundPanner.maxDistance = this.maxDistance;
  61810. this._soundPanner.refDistance = this.refDistance;
  61811. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61812. this._soundPanner.panningModel = this._panningModel;
  61813. }
  61814. }
  61815. };
  61816. Sound.prototype.switchPanningModelToHRTF = function () {
  61817. this._panningModel = "HRTF";
  61818. this._switchPanningModel();
  61819. };
  61820. Sound.prototype.switchPanningModelToEqualPower = function () {
  61821. this._panningModel = "equalpower";
  61822. this._switchPanningModel();
  61823. };
  61824. Sound.prototype._switchPanningModel = function () {
  61825. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61826. this._soundPanner.panningModel = this._panningModel;
  61827. }
  61828. };
  61829. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61830. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61831. if (this._isOutputConnected) {
  61832. this._ouputAudioNode.disconnect();
  61833. }
  61834. this._ouputAudioNode.connect(soundTrackAudioNode);
  61835. this._isOutputConnected = true;
  61836. }
  61837. };
  61838. /**
  61839. * Transform this sound into a directional source
  61840. * @param coneInnerAngle Size of the inner cone in degree
  61841. * @param coneOuterAngle Size of the outer cone in degree
  61842. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61843. */
  61844. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61845. if (coneOuterAngle < coneInnerAngle) {
  61846. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61847. return;
  61848. }
  61849. this._coneInnerAngle = coneInnerAngle;
  61850. this._coneOuterAngle = coneOuterAngle;
  61851. this._coneOuterGain = coneOuterGain;
  61852. this._isDirectional = true;
  61853. if (this.isPlaying && this.loop) {
  61854. this.stop();
  61855. this.play();
  61856. }
  61857. };
  61858. Sound.prototype.setPosition = function (newPosition) {
  61859. this._position = newPosition;
  61860. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61861. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61862. }
  61863. };
  61864. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61865. this._localDirection = newLocalDirection;
  61866. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61867. this._updateDirection();
  61868. }
  61869. };
  61870. Sound.prototype._updateDirection = function () {
  61871. if (!this._connectedMesh || !this._soundPanner) {
  61872. return;
  61873. }
  61874. var mat = this._connectedMesh.getWorldMatrix();
  61875. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61876. direction.normalize();
  61877. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61878. };
  61879. Sound.prototype.updateDistanceFromListener = function () {
  61880. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61881. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61882. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61883. }
  61884. };
  61885. Sound.prototype.setAttenuationFunction = function (callback) {
  61886. this._customAttenuationFunction = callback;
  61887. };
  61888. /**
  61889. * Play the sound
  61890. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61891. * @param offset (optional) Start the sound setting it at a specific time
  61892. */
  61893. Sound.prototype.play = function (time, offset) {
  61894. var _this = this;
  61895. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61896. try {
  61897. if (this._startOffset < 0) {
  61898. time = -this._startOffset;
  61899. this._startOffset = 0;
  61900. }
  61901. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61902. if (!this._soundSource || !this._streamingSource) {
  61903. if (this.spatialSound && this._soundPanner) {
  61904. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61905. if (this._isDirectional) {
  61906. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61907. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61908. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61909. if (this._connectedMesh) {
  61910. this._updateDirection();
  61911. }
  61912. else {
  61913. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61914. }
  61915. }
  61916. }
  61917. }
  61918. if (this._streaming) {
  61919. if (!this._streamingSource) {
  61920. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61921. this._htmlAudioElement.onended = function () { _this._onended(); };
  61922. this._htmlAudioElement.playbackRate = this._playbackRate;
  61923. }
  61924. this._streamingSource.disconnect();
  61925. this._streamingSource.connect(this._inputAudioNode);
  61926. this._htmlAudioElement.play();
  61927. }
  61928. else {
  61929. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61930. this._soundSource.buffer = this._audioBuffer;
  61931. this._soundSource.connect(this._inputAudioNode);
  61932. this._soundSource.loop = this.loop;
  61933. this._soundSource.playbackRate.value = this._playbackRate;
  61934. this._soundSource.onended = function () { _this._onended(); };
  61935. if (this._soundSource.buffer) {
  61936. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61937. }
  61938. }
  61939. this._startTime = startTime;
  61940. this.isPlaying = true;
  61941. this.isPaused = false;
  61942. }
  61943. catch (ex) {
  61944. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  61945. }
  61946. }
  61947. };
  61948. Sound.prototype._onended = function () {
  61949. this.isPlaying = false;
  61950. if (this.onended) {
  61951. this.onended();
  61952. }
  61953. };
  61954. /**
  61955. * Stop the sound
  61956. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  61957. */
  61958. Sound.prototype.stop = function (time) {
  61959. if (this.isPlaying) {
  61960. if (this._streaming) {
  61961. this._htmlAudioElement.pause();
  61962. // Test needed for Firefox or it will generate an Invalid State Error
  61963. if (this._htmlAudioElement.currentTime > 0) {
  61964. this._htmlAudioElement.currentTime = 0;
  61965. }
  61966. }
  61967. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  61968. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61969. this._soundSource.stop(stopTime);
  61970. this._soundSource.onended = function () { };
  61971. if (!this.isPaused) {
  61972. this._startOffset = 0;
  61973. }
  61974. }
  61975. this.isPlaying = false;
  61976. }
  61977. };
  61978. Sound.prototype.pause = function () {
  61979. if (this.isPlaying) {
  61980. this.isPaused = true;
  61981. if (this._streaming) {
  61982. this._htmlAudioElement.pause();
  61983. }
  61984. else if (BABYLON.Engine.audioEngine.audioContext) {
  61985. this.stop(0);
  61986. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  61987. }
  61988. }
  61989. };
  61990. Sound.prototype.setVolume = function (newVolume, time) {
  61991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  61992. if (time && BABYLON.Engine.audioEngine.audioContext) {
  61993. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  61994. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  61995. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  61996. }
  61997. else {
  61998. this._soundGain.gain.value = newVolume;
  61999. }
  62000. }
  62001. this._volume = newVolume;
  62002. };
  62003. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62004. this._playbackRate = newPlaybackRate;
  62005. if (this.isPlaying) {
  62006. if (this._streaming) {
  62007. this._htmlAudioElement.playbackRate = this._playbackRate;
  62008. }
  62009. else if (this._soundSource) {
  62010. this._soundSource.playbackRate.value = this._playbackRate;
  62011. }
  62012. }
  62013. };
  62014. Sound.prototype.getVolume = function () {
  62015. return this._volume;
  62016. };
  62017. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62018. var _this = this;
  62019. if (this._connectedMesh && this._registerFunc) {
  62020. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62021. this._registerFunc = null;
  62022. }
  62023. this._connectedMesh = meshToConnectTo;
  62024. if (!this.spatialSound) {
  62025. this.spatialSound = true;
  62026. this._createSpatialParameters();
  62027. if (this.isPlaying && this.loop) {
  62028. this.stop();
  62029. this.play();
  62030. }
  62031. }
  62032. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62033. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62034. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62035. };
  62036. Sound.prototype.detachFromMesh = function () {
  62037. if (this._connectedMesh && this._registerFunc) {
  62038. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62039. this._registerFunc = null;
  62040. this._connectedMesh = null;
  62041. }
  62042. };
  62043. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62044. if (!node.getBoundingInfo) {
  62045. return;
  62046. }
  62047. var mesh = node;
  62048. var boundingInfo = mesh.getBoundingInfo();
  62049. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62050. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62051. this._updateDirection();
  62052. }
  62053. };
  62054. Sound.prototype.clone = function () {
  62055. var _this = this;
  62056. if (!this._streaming) {
  62057. var setBufferAndRun = function () {
  62058. if (_this._isReadyToPlay) {
  62059. clonedSound._audioBuffer = _this.getAudioBuffer();
  62060. clonedSound._isReadyToPlay = true;
  62061. if (clonedSound.autoplay) {
  62062. clonedSound.play();
  62063. }
  62064. }
  62065. else {
  62066. window.setTimeout(setBufferAndRun, 300);
  62067. }
  62068. };
  62069. var currentOptions = {
  62070. autoplay: this.autoplay, loop: this.loop,
  62071. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62072. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62073. refDistance: this.refDistance, distanceModel: this.distanceModel
  62074. };
  62075. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62076. if (this.useCustomAttenuation) {
  62077. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62078. }
  62079. clonedSound.setPosition(this._position);
  62080. clonedSound.setPlaybackRate(this._playbackRate);
  62081. setBufferAndRun();
  62082. return clonedSound;
  62083. }
  62084. // Can't clone a streaming sound
  62085. else {
  62086. return null;
  62087. }
  62088. };
  62089. Sound.prototype.getAudioBuffer = function () {
  62090. return this._audioBuffer;
  62091. };
  62092. Sound.prototype.serialize = function () {
  62093. var serializationObject = {
  62094. name: this.name,
  62095. url: this.name,
  62096. autoplay: this.autoplay,
  62097. loop: this.loop,
  62098. volume: this._volume,
  62099. spatialSound: this.spatialSound,
  62100. maxDistance: this.maxDistance,
  62101. rolloffFactor: this.rolloffFactor,
  62102. refDistance: this.refDistance,
  62103. distanceModel: this.distanceModel,
  62104. playbackRate: this._playbackRate,
  62105. panningModel: this._panningModel,
  62106. soundTrackId: this.soundTrackId
  62107. };
  62108. if (this.spatialSound) {
  62109. if (this._connectedMesh)
  62110. serializationObject.connectedMeshId = this._connectedMesh.id;
  62111. serializationObject.position = this._position.asArray();
  62112. serializationObject.refDistance = this.refDistance;
  62113. serializationObject.distanceModel = this.distanceModel;
  62114. serializationObject.isDirectional = this._isDirectional;
  62115. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62116. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62117. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62118. serializationObject.coneOuterGain = this._coneOuterGain;
  62119. }
  62120. return serializationObject;
  62121. };
  62122. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62123. var soundName = parsedSound.name;
  62124. var soundUrl;
  62125. if (parsedSound.url) {
  62126. soundUrl = rootUrl + parsedSound.url;
  62127. }
  62128. else {
  62129. soundUrl = rootUrl + soundName;
  62130. }
  62131. var options = {
  62132. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62133. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62134. rolloffFactor: parsedSound.rolloffFactor,
  62135. refDistance: parsedSound.refDistance,
  62136. distanceModel: parsedSound.distanceModel,
  62137. playbackRate: parsedSound.playbackRate
  62138. };
  62139. var newSound;
  62140. if (!sourceSound) {
  62141. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62142. scene._addPendingData(newSound);
  62143. }
  62144. else {
  62145. var setBufferAndRun = function () {
  62146. if (sourceSound._isReadyToPlay) {
  62147. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62148. newSound._isReadyToPlay = true;
  62149. if (newSound.autoplay) {
  62150. newSound.play();
  62151. }
  62152. }
  62153. else {
  62154. window.setTimeout(setBufferAndRun, 300);
  62155. }
  62156. };
  62157. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62158. setBufferAndRun();
  62159. }
  62160. if (parsedSound.position) {
  62161. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62162. newSound.setPosition(soundPosition);
  62163. }
  62164. if (parsedSound.isDirectional) {
  62165. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62166. if (parsedSound.localDirectionToMesh) {
  62167. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62168. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62169. }
  62170. }
  62171. if (parsedSound.connectedMeshId) {
  62172. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62173. if (connectedMesh) {
  62174. newSound.attachToMesh(connectedMesh);
  62175. }
  62176. }
  62177. return newSound;
  62178. };
  62179. return Sound;
  62180. }());
  62181. BABYLON.Sound = Sound;
  62182. })(BABYLON || (BABYLON = {}));
  62183. //# sourceMappingURL=babylon.sound.js.map
  62184. var BABYLON;
  62185. (function (BABYLON) {
  62186. var SoundTrack = /** @class */ (function () {
  62187. function SoundTrack(scene, options) {
  62188. this.id = -1;
  62189. this._isMainTrack = false;
  62190. this._isInitialized = false;
  62191. this._scene = scene;
  62192. this.soundCollection = new Array();
  62193. this._options = options;
  62194. if (!this._isMainTrack) {
  62195. this._scene.soundTracks.push(this);
  62196. this.id = this._scene.soundTracks.length - 1;
  62197. }
  62198. }
  62199. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62200. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62201. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62202. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62203. if (this._options) {
  62204. if (this._options.volume) {
  62205. this._outputAudioNode.gain.value = this._options.volume;
  62206. }
  62207. if (this._options.mainTrack) {
  62208. this._isMainTrack = this._options.mainTrack;
  62209. }
  62210. }
  62211. this._isInitialized = true;
  62212. }
  62213. };
  62214. SoundTrack.prototype.dispose = function () {
  62215. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62216. if (this._connectedAnalyser) {
  62217. this._connectedAnalyser.stopDebugCanvas();
  62218. }
  62219. while (this.soundCollection.length) {
  62220. this.soundCollection[0].dispose();
  62221. }
  62222. if (this._outputAudioNode) {
  62223. this._outputAudioNode.disconnect();
  62224. }
  62225. this._outputAudioNode = null;
  62226. }
  62227. };
  62228. SoundTrack.prototype.AddSound = function (sound) {
  62229. if (!this._isInitialized) {
  62230. this._initializeSoundTrackAudioGraph();
  62231. }
  62232. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62233. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62234. }
  62235. if (sound.soundTrackId) {
  62236. if (sound.soundTrackId === -1) {
  62237. this._scene.mainSoundTrack.RemoveSound(sound);
  62238. }
  62239. else {
  62240. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62241. }
  62242. }
  62243. this.soundCollection.push(sound);
  62244. sound.soundTrackId = this.id;
  62245. };
  62246. SoundTrack.prototype.RemoveSound = function (sound) {
  62247. var index = this.soundCollection.indexOf(sound);
  62248. if (index !== -1) {
  62249. this.soundCollection.splice(index, 1);
  62250. }
  62251. };
  62252. SoundTrack.prototype.setVolume = function (newVolume) {
  62253. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62254. this._outputAudioNode.gain.value = newVolume;
  62255. }
  62256. };
  62257. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62258. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62259. for (var i = 0; i < this.soundCollection.length; i++) {
  62260. this.soundCollection[i].switchPanningModelToHRTF();
  62261. }
  62262. }
  62263. };
  62264. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62265. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62266. for (var i = 0; i < this.soundCollection.length; i++) {
  62267. this.soundCollection[i].switchPanningModelToEqualPower();
  62268. }
  62269. }
  62270. };
  62271. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62272. if (this._connectedAnalyser) {
  62273. this._connectedAnalyser.stopDebugCanvas();
  62274. }
  62275. this._connectedAnalyser = analyser;
  62276. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62277. this._outputAudioNode.disconnect();
  62278. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62279. }
  62280. };
  62281. return SoundTrack;
  62282. }());
  62283. BABYLON.SoundTrack = SoundTrack;
  62284. })(BABYLON || (BABYLON = {}));
  62285. //# sourceMappingURL=babylon.soundtrack.js.map
  62286. var BABYLON;
  62287. (function (BABYLON) {
  62288. var Analyser = /** @class */ (function () {
  62289. function Analyser(scene) {
  62290. this.SMOOTHING = 0.75;
  62291. this.FFT_SIZE = 512;
  62292. this.BARGRAPHAMPLITUDE = 256;
  62293. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62294. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62295. this._scene = scene;
  62296. this._audioEngine = BABYLON.Engine.audioEngine;
  62297. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62298. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62299. this._webAudioAnalyser.minDecibels = -140;
  62300. this._webAudioAnalyser.maxDecibels = 0;
  62301. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62302. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62303. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62304. }
  62305. }
  62306. Analyser.prototype.getFrequencyBinCount = function () {
  62307. if (this._audioEngine.canUseWebAudio) {
  62308. return this._webAudioAnalyser.frequencyBinCount;
  62309. }
  62310. else {
  62311. return 0;
  62312. }
  62313. };
  62314. Analyser.prototype.getByteFrequencyData = function () {
  62315. if (this._audioEngine.canUseWebAudio) {
  62316. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62317. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62318. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62319. }
  62320. return this._byteFreqs;
  62321. };
  62322. Analyser.prototype.getByteTimeDomainData = function () {
  62323. if (this._audioEngine.canUseWebAudio) {
  62324. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62325. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62326. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62327. }
  62328. return this._byteTime;
  62329. };
  62330. Analyser.prototype.getFloatFrequencyData = function () {
  62331. if (this._audioEngine.canUseWebAudio) {
  62332. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62333. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62334. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62335. }
  62336. return this._floatFreqs;
  62337. };
  62338. Analyser.prototype.drawDebugCanvas = function () {
  62339. var _this = this;
  62340. if (this._audioEngine.canUseWebAudio) {
  62341. if (!this._debugCanvas) {
  62342. this._debugCanvas = document.createElement("canvas");
  62343. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62344. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62345. this._debugCanvas.style.position = "absolute";
  62346. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62347. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62348. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62349. document.body.appendChild(this._debugCanvas);
  62350. this._registerFunc = function () {
  62351. _this.drawDebugCanvas();
  62352. };
  62353. this._scene.registerBeforeRender(this._registerFunc);
  62354. }
  62355. if (this._registerFunc && this._debugCanvasContext) {
  62356. var workingArray = this.getByteFrequencyData();
  62357. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62358. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62359. // Draw the frequency domain chart.
  62360. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62361. var value = workingArray[i];
  62362. var percent = value / this.BARGRAPHAMPLITUDE;
  62363. var height = this.DEBUGCANVASSIZE.height * percent;
  62364. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62365. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62366. var hue = i / this.getFrequencyBinCount() * 360;
  62367. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62368. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62369. }
  62370. }
  62371. }
  62372. };
  62373. Analyser.prototype.stopDebugCanvas = function () {
  62374. if (this._debugCanvas) {
  62375. if (this._registerFunc) {
  62376. this._scene.unregisterBeforeRender(this._registerFunc);
  62377. this._registerFunc = null;
  62378. }
  62379. document.body.removeChild(this._debugCanvas);
  62380. this._debugCanvas = null;
  62381. this._debugCanvasContext = null;
  62382. }
  62383. };
  62384. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62385. if (this._audioEngine.canUseWebAudio) {
  62386. inputAudioNode.connect(this._webAudioAnalyser);
  62387. this._webAudioAnalyser.connect(outputAudioNode);
  62388. }
  62389. };
  62390. Analyser.prototype.dispose = function () {
  62391. if (this._audioEngine.canUseWebAudio) {
  62392. this._webAudioAnalyser.disconnect();
  62393. }
  62394. };
  62395. return Analyser;
  62396. }());
  62397. BABYLON.Analyser = Analyser;
  62398. })(BABYLON || (BABYLON = {}));
  62399. //# sourceMappingURL=babylon.analyser.js.map
  62400. var BABYLON;
  62401. (function (BABYLON) {
  62402. var CubeTexture = /** @class */ (function (_super) {
  62403. __extends(CubeTexture, _super);
  62404. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62405. if (extensions === void 0) { extensions = null; }
  62406. if (noMipmap === void 0) { noMipmap = false; }
  62407. if (files === void 0) { files = null; }
  62408. if (onLoad === void 0) { onLoad = null; }
  62409. if (onError === void 0) { onError = null; }
  62410. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62411. if (prefiltered === void 0) { prefiltered = false; }
  62412. if (forcedExtension === void 0) { forcedExtension = null; }
  62413. var _this = _super.call(this, scene) || this;
  62414. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62415. /**
  62416. * Gets or sets the center of the bounding box associated with the cube texture
  62417. * It must define where the camera used to render the texture was set
  62418. */
  62419. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62420. _this._rotationY = 0;
  62421. _this.name = rootUrl;
  62422. _this.url = rootUrl;
  62423. _this._noMipmap = noMipmap;
  62424. _this.hasAlpha = false;
  62425. _this._format = format;
  62426. _this._prefiltered = prefiltered;
  62427. _this.isCube = true;
  62428. _this._textureMatrix = BABYLON.Matrix.Identity();
  62429. if (prefiltered) {
  62430. _this.gammaSpace = false;
  62431. }
  62432. if (!rootUrl && !files) {
  62433. return _this;
  62434. }
  62435. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62436. var lastDot = rootUrl.lastIndexOf(".");
  62437. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62438. var isDDS = (extension === ".dds");
  62439. if (!files) {
  62440. if (!isDDS && !extensions) {
  62441. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62442. }
  62443. files = [];
  62444. if (extensions) {
  62445. for (var index = 0; index < extensions.length; index++) {
  62446. files.push(rootUrl + extensions[index]);
  62447. }
  62448. }
  62449. }
  62450. _this._files = files;
  62451. if (!_this._texture) {
  62452. if (!scene.useDelayedTextureLoading) {
  62453. if (prefiltered) {
  62454. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62455. }
  62456. else {
  62457. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62458. }
  62459. }
  62460. else {
  62461. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62462. }
  62463. }
  62464. else if (onLoad) {
  62465. if (_this._texture.isReady) {
  62466. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62467. }
  62468. else {
  62469. _this._texture.onLoadedObservable.add(onLoad);
  62470. }
  62471. }
  62472. return _this;
  62473. }
  62474. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62475. get: function () {
  62476. return this._boundingBoxSize;
  62477. },
  62478. /**
  62479. * Gets or sets the size of the bounding box associated with the cube texture
  62480. * When defined, the cubemap will switch to local mode
  62481. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62482. * @example https://www.babylonjs-playground.com/#RNASML
  62483. */
  62484. set: function (value) {
  62485. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62486. return;
  62487. }
  62488. this._boundingBoxSize = value;
  62489. var scene = this.getScene();
  62490. if (scene) {
  62491. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62492. }
  62493. },
  62494. enumerable: true,
  62495. configurable: true
  62496. });
  62497. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62498. /**
  62499. * Gets texture matrix rotation angle around Y axis radians.
  62500. */
  62501. get: function () {
  62502. return this._rotationY;
  62503. },
  62504. /**
  62505. * Sets texture matrix rotation angle around Y axis in radians.
  62506. */
  62507. set: function (value) {
  62508. this._rotationY = value;
  62509. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62510. },
  62511. enumerable: true,
  62512. configurable: true
  62513. });
  62514. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62515. var rootUrlKey = "";
  62516. files.forEach(function (url) { return rootUrlKey += url; });
  62517. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62518. };
  62519. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62520. if (forcedExtension === void 0) { forcedExtension = null; }
  62521. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62522. };
  62523. // Methods
  62524. CubeTexture.prototype.delayLoad = function () {
  62525. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62526. return;
  62527. }
  62528. var scene = this.getScene();
  62529. if (!scene) {
  62530. return;
  62531. }
  62532. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62533. this._texture = this._getFromCache(this.url, this._noMipmap);
  62534. if (!this._texture) {
  62535. if (this._prefiltered) {
  62536. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62537. }
  62538. else {
  62539. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62540. }
  62541. }
  62542. };
  62543. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62544. return this._textureMatrix;
  62545. };
  62546. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62547. this._textureMatrix = value;
  62548. };
  62549. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62550. var texture = BABYLON.SerializationHelper.Parse(function () {
  62551. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62552. }, parsedTexture, scene);
  62553. // Local Cubemaps
  62554. if (parsedTexture.boundingBoxPosition) {
  62555. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62556. }
  62557. if (parsedTexture.boundingBoxSize) {
  62558. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62559. }
  62560. // Animations
  62561. if (parsedTexture.animations) {
  62562. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62563. var parsedAnimation = parsedTexture.animations[animationIndex];
  62564. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62565. }
  62566. }
  62567. return texture;
  62568. };
  62569. CubeTexture.prototype.clone = function () {
  62570. var _this = this;
  62571. return BABYLON.SerializationHelper.Clone(function () {
  62572. var scene = _this.getScene();
  62573. if (!scene) {
  62574. return _this;
  62575. }
  62576. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62577. }, this);
  62578. };
  62579. __decorate([
  62580. BABYLON.serialize("rotationY")
  62581. ], CubeTexture.prototype, "_rotationY", void 0);
  62582. return CubeTexture;
  62583. }(BABYLON.BaseTexture));
  62584. BABYLON.CubeTexture = CubeTexture;
  62585. })(BABYLON || (BABYLON = {}));
  62586. //# sourceMappingURL=babylon.cubeTexture.js.map
  62587. var BABYLON;
  62588. (function (BABYLON) {
  62589. var RenderTargetTexture = /** @class */ (function (_super) {
  62590. __extends(RenderTargetTexture, _super);
  62591. /**
  62592. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62593. * or used a shadow, depth texture...
  62594. * @param name The friendly name of the texture
  62595. * @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)
  62596. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62597. * @param generateMipMaps True if mip maps need to be generated after render.
  62598. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62599. * @param type The type of the buffer in the RTT (int, half float, float...)
  62600. * @param isCube True if a cube texture needs to be created
  62601. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62602. * @param generateDepthBuffer True to generate a depth buffer
  62603. * @param generateStencilBuffer True to generate a stencil buffer
  62604. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62605. */
  62606. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62607. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62608. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62609. if (isCube === void 0) { isCube = false; }
  62610. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62611. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62612. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62613. if (isMulti === void 0) { isMulti = false; }
  62614. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62615. _this.isCube = isCube;
  62616. /**
  62617. * Use this list to define the list of mesh you want to render.
  62618. */
  62619. _this.renderList = new Array();
  62620. _this.renderParticles = true;
  62621. _this.renderSprites = false;
  62622. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62623. _this.ignoreCameraViewport = false;
  62624. // Events
  62625. /**
  62626. * An event triggered when the texture is unbind.
  62627. */
  62628. _this.onBeforeBindObservable = new BABYLON.Observable();
  62629. /**
  62630. * An event triggered when the texture is unbind.
  62631. */
  62632. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62633. /**
  62634. * An event triggered before rendering the texture
  62635. */
  62636. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62637. /**
  62638. * An event triggered after rendering the texture
  62639. */
  62640. _this.onAfterRenderObservable = new BABYLON.Observable();
  62641. /**
  62642. * An event triggered after the texture clear
  62643. */
  62644. _this.onClearObservable = new BABYLON.Observable();
  62645. _this._currentRefreshId = -1;
  62646. _this._refreshRate = 1;
  62647. _this._samples = 1;
  62648. /**
  62649. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62650. * It must define where the camera used to render the texture is set
  62651. */
  62652. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62653. scene = _this.getScene();
  62654. if (!scene) {
  62655. return _this;
  62656. }
  62657. _this._engine = scene.getEngine();
  62658. _this.name = name;
  62659. _this.isRenderTarget = true;
  62660. _this._initialSizeParameter = size;
  62661. _this._processSizeParameter(size);
  62662. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62663. });
  62664. _this._generateMipMaps = generateMipMaps ? true : false;
  62665. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62666. // Rendering groups
  62667. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62668. if (isMulti) {
  62669. return _this;
  62670. }
  62671. _this._renderTargetOptions = {
  62672. generateMipMaps: generateMipMaps,
  62673. type: type,
  62674. samplingMode: samplingMode,
  62675. generateDepthBuffer: generateDepthBuffer,
  62676. generateStencilBuffer: generateStencilBuffer
  62677. };
  62678. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62679. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62680. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62681. }
  62682. if (isCube) {
  62683. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62684. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62685. _this._textureMatrix = BABYLON.Matrix.Identity();
  62686. }
  62687. else {
  62688. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62689. }
  62690. return _this;
  62691. }
  62692. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62693. get: function () {
  62694. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62695. },
  62696. enumerable: true,
  62697. configurable: true
  62698. });
  62699. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62700. get: function () {
  62701. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62702. },
  62703. enumerable: true,
  62704. configurable: true
  62705. });
  62706. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62707. get: function () {
  62708. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62709. },
  62710. enumerable: true,
  62711. configurable: true
  62712. });
  62713. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62714. set: function (callback) {
  62715. if (this._onAfterUnbindObserver) {
  62716. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62717. }
  62718. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62719. },
  62720. enumerable: true,
  62721. configurable: true
  62722. });
  62723. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62724. set: function (callback) {
  62725. if (this._onBeforeRenderObserver) {
  62726. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62727. }
  62728. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62729. },
  62730. enumerable: true,
  62731. configurable: true
  62732. });
  62733. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62734. set: function (callback) {
  62735. if (this._onAfterRenderObserver) {
  62736. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62737. }
  62738. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62739. },
  62740. enumerable: true,
  62741. configurable: true
  62742. });
  62743. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62744. set: function (callback) {
  62745. if (this._onClearObserver) {
  62746. this.onClearObservable.remove(this._onClearObserver);
  62747. }
  62748. this._onClearObserver = this.onClearObservable.add(callback);
  62749. },
  62750. enumerable: true,
  62751. configurable: true
  62752. });
  62753. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62754. get: function () {
  62755. return this._renderTargetOptions;
  62756. },
  62757. enumerable: true,
  62758. configurable: true
  62759. });
  62760. RenderTargetTexture.prototype._onRatioRescale = function () {
  62761. if (this._sizeRatio) {
  62762. this.resize(this._initialSizeParameter);
  62763. }
  62764. };
  62765. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62766. get: function () {
  62767. return this._boundingBoxSize;
  62768. },
  62769. /**
  62770. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62771. * When defined, the cubemap will switch to local mode
  62772. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62773. * @example https://www.babylonjs-playground.com/#RNASML
  62774. */
  62775. set: function (value) {
  62776. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62777. return;
  62778. }
  62779. this._boundingBoxSize = value;
  62780. var scene = this.getScene();
  62781. if (scene) {
  62782. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62783. }
  62784. },
  62785. enumerable: true,
  62786. configurable: true
  62787. });
  62788. /**
  62789. * Creates a depth stencil texture.
  62790. * This is only available in WebGL 2 or with the depth texture extension available.
  62791. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62792. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62793. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62794. */
  62795. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62796. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62797. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62798. if (generateStencil === void 0) { generateStencil = false; }
  62799. if (!this.getScene()) {
  62800. return;
  62801. }
  62802. var engine = this.getScene().getEngine();
  62803. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62804. bilinearFiltering: bilinearFiltering,
  62805. comparisonFunction: comparisonFunction,
  62806. generateStencil: generateStencil,
  62807. isCube: this.isCube
  62808. });
  62809. engine.setFrameBufferDepthStencilTexture(this);
  62810. };
  62811. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62812. if (size.ratio) {
  62813. this._sizeRatio = size.ratio;
  62814. this._size = {
  62815. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62816. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62817. };
  62818. }
  62819. else {
  62820. this._size = size;
  62821. }
  62822. };
  62823. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62824. get: function () {
  62825. return this._samples;
  62826. },
  62827. set: function (value) {
  62828. if (this._samples === value) {
  62829. return;
  62830. }
  62831. var scene = this.getScene();
  62832. if (!scene) {
  62833. return;
  62834. }
  62835. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62836. },
  62837. enumerable: true,
  62838. configurable: true
  62839. });
  62840. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62841. this._currentRefreshId = -1;
  62842. };
  62843. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62844. get: function () {
  62845. return this._refreshRate;
  62846. },
  62847. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62848. set: function (value) {
  62849. this._refreshRate = value;
  62850. this.resetRefreshCounter();
  62851. },
  62852. enumerable: true,
  62853. configurable: true
  62854. });
  62855. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62856. if (!this._postProcessManager) {
  62857. var scene = this.getScene();
  62858. if (!scene) {
  62859. return;
  62860. }
  62861. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62862. this._postProcesses = new Array();
  62863. }
  62864. this._postProcesses.push(postProcess);
  62865. this._postProcesses[0].autoClear = false;
  62866. };
  62867. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62868. if (!this._postProcesses) {
  62869. return;
  62870. }
  62871. if (dispose) {
  62872. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62873. var postProcess = _a[_i];
  62874. postProcess.dispose();
  62875. }
  62876. }
  62877. this._postProcesses = [];
  62878. };
  62879. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62880. if (!this._postProcesses) {
  62881. return;
  62882. }
  62883. var index = this._postProcesses.indexOf(postProcess);
  62884. if (index === -1) {
  62885. return;
  62886. }
  62887. this._postProcesses.splice(index, 1);
  62888. if (this._postProcesses.length > 0) {
  62889. this._postProcesses[0].autoClear = false;
  62890. }
  62891. };
  62892. RenderTargetTexture.prototype._shouldRender = function () {
  62893. if (this._currentRefreshId === -1) { // At least render once
  62894. this._currentRefreshId = 1;
  62895. return true;
  62896. }
  62897. if (this.refreshRate === this._currentRefreshId) {
  62898. this._currentRefreshId = 1;
  62899. return true;
  62900. }
  62901. this._currentRefreshId++;
  62902. return false;
  62903. };
  62904. RenderTargetTexture.prototype.getRenderSize = function () {
  62905. if (this._size.width) {
  62906. return this._size.width;
  62907. }
  62908. return this._size;
  62909. };
  62910. RenderTargetTexture.prototype.getRenderWidth = function () {
  62911. if (this._size.width) {
  62912. return this._size.width;
  62913. }
  62914. return this._size;
  62915. };
  62916. RenderTargetTexture.prototype.getRenderHeight = function () {
  62917. if (this._size.width) {
  62918. return this._size.height;
  62919. }
  62920. return this._size;
  62921. };
  62922. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62923. get: function () {
  62924. return true;
  62925. },
  62926. enumerable: true,
  62927. configurable: true
  62928. });
  62929. RenderTargetTexture.prototype.scale = function (ratio) {
  62930. var newSize = this.getRenderSize() * ratio;
  62931. this.resize(newSize);
  62932. };
  62933. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62934. if (this.isCube) {
  62935. return this._textureMatrix;
  62936. }
  62937. return _super.prototype.getReflectionTextureMatrix.call(this);
  62938. };
  62939. RenderTargetTexture.prototype.resize = function (size) {
  62940. this.releaseInternalTexture();
  62941. var scene = this.getScene();
  62942. if (!scene) {
  62943. return;
  62944. }
  62945. this._processSizeParameter(size);
  62946. if (this.isCube) {
  62947. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  62948. }
  62949. else {
  62950. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  62951. }
  62952. };
  62953. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  62954. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  62955. if (dumpForDebug === void 0) { dumpForDebug = false; }
  62956. var scene = this.getScene();
  62957. if (!scene) {
  62958. return;
  62959. }
  62960. var engine = scene.getEngine();
  62961. if (this.useCameraPostProcesses !== undefined) {
  62962. useCameraPostProcess = this.useCameraPostProcesses;
  62963. }
  62964. if (this._waitingRenderList) {
  62965. this.renderList = [];
  62966. for (var index = 0; index < this._waitingRenderList.length; index++) {
  62967. var id = this._waitingRenderList[index];
  62968. var mesh_1 = scene.getMeshByID(id);
  62969. if (mesh_1) {
  62970. this.renderList.push(mesh_1);
  62971. }
  62972. }
  62973. delete this._waitingRenderList;
  62974. }
  62975. // Is predicate defined?
  62976. if (this.renderListPredicate) {
  62977. if (this.renderList) {
  62978. this.renderList.splice(0); // Clear previous renderList
  62979. }
  62980. else {
  62981. this.renderList = [];
  62982. }
  62983. var scene = this.getScene();
  62984. if (!scene) {
  62985. return;
  62986. }
  62987. var sceneMeshes = scene.meshes;
  62988. for (var index = 0; index < sceneMeshes.length; index++) {
  62989. var mesh = sceneMeshes[index];
  62990. if (this.renderListPredicate(mesh)) {
  62991. this.renderList.push(mesh);
  62992. }
  62993. }
  62994. }
  62995. this.onBeforeBindObservable.notifyObservers(this);
  62996. // Set custom projection.
  62997. // Needs to be before binding to prevent changing the aspect ratio.
  62998. var camera;
  62999. if (this.activeCamera) {
  63000. camera = this.activeCamera;
  63001. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63002. if (this.activeCamera !== scene.activeCamera) {
  63003. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63004. }
  63005. }
  63006. else {
  63007. camera = scene.activeCamera;
  63008. if (camera) {
  63009. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63010. }
  63011. }
  63012. // Prepare renderingManager
  63013. this._renderingManager.reset();
  63014. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63015. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63016. var sceneRenderId = scene.getRenderId();
  63017. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63018. var mesh = currentRenderList[meshIndex];
  63019. if (mesh) {
  63020. if (!mesh.isReady(this.refreshRate === 0)) {
  63021. this.resetRefreshCounter();
  63022. continue;
  63023. }
  63024. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63025. var isMasked = void 0;
  63026. if (!this.renderList && camera) {
  63027. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63028. }
  63029. else {
  63030. isMasked = false;
  63031. }
  63032. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63033. mesh._activate(sceneRenderId);
  63034. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63035. var subMesh = mesh.subMeshes[subIndex];
  63036. scene._activeIndices.addCount(subMesh.indexCount, false);
  63037. this._renderingManager.dispatch(subMesh, mesh);
  63038. }
  63039. }
  63040. }
  63041. }
  63042. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63043. var particleSystem = scene.particleSystems[particleIndex];
  63044. var emitter = particleSystem.emitter;
  63045. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63046. continue;
  63047. }
  63048. if (currentRenderList.indexOf(emitter) >= 0) {
  63049. this._renderingManager.dispatchParticles(particleSystem);
  63050. }
  63051. }
  63052. if (this.isCube) {
  63053. for (var face = 0; face < 6; face++) {
  63054. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63055. scene.incrementRenderId();
  63056. scene.resetCachedMaterial();
  63057. }
  63058. }
  63059. else {
  63060. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63061. }
  63062. this.onAfterUnbindObservable.notifyObservers(this);
  63063. if (scene.activeCamera) {
  63064. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63065. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63066. }
  63067. engine.setViewport(scene.activeCamera.viewport);
  63068. }
  63069. scene.resetCachedMaterial();
  63070. };
  63071. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63072. var minimum = 128;
  63073. var x = renderDimension * scale;
  63074. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63075. // Ensure we don't exceed the render dimension (while staying POT)
  63076. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63077. };
  63078. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63079. var _this = this;
  63080. if (!this._texture) {
  63081. return;
  63082. }
  63083. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63084. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63085. });
  63086. };
  63087. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63088. var scene = this.getScene();
  63089. if (!scene) {
  63090. return;
  63091. }
  63092. var engine = scene.getEngine();
  63093. if (!this._texture) {
  63094. return;
  63095. }
  63096. // Bind
  63097. if (this._postProcessManager) {
  63098. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63099. }
  63100. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63101. if (this._texture) {
  63102. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63103. }
  63104. }
  63105. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63106. // Clear
  63107. if (this.onClearObservable.hasObservers()) {
  63108. this.onClearObservable.notifyObservers(engine);
  63109. }
  63110. else {
  63111. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63112. }
  63113. if (!this._doNotChangeAspectRatio) {
  63114. scene.updateTransformMatrix(true);
  63115. }
  63116. // Render
  63117. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63118. if (this._postProcessManager) {
  63119. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63120. }
  63121. else if (useCameraPostProcess) {
  63122. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63123. }
  63124. if (!this._doNotChangeAspectRatio) {
  63125. scene.updateTransformMatrix(true);
  63126. }
  63127. // Dump ?
  63128. if (dumpForDebug) {
  63129. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63130. }
  63131. // Unbind
  63132. if (!this.isCube || faceIndex === 5) {
  63133. if (this.isCube) {
  63134. if (faceIndex === 5) {
  63135. engine.generateMipMapsForCubemap(this._texture);
  63136. }
  63137. }
  63138. this.unbindFrameBuffer(engine, faceIndex);
  63139. }
  63140. else {
  63141. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63142. }
  63143. };
  63144. /**
  63145. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63146. * This allowed control for front to back rendering or reversly depending of the special needs.
  63147. *
  63148. * @param renderingGroupId The rendering group id corresponding to its index
  63149. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63150. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63151. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63152. */
  63153. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63154. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63155. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63156. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63157. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63158. };
  63159. /**
  63160. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63161. *
  63162. * @param renderingGroupId The rendering group id corresponding to its index
  63163. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63164. */
  63165. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63166. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63167. };
  63168. RenderTargetTexture.prototype.clone = function () {
  63169. var textureSize = this.getSize();
  63170. 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);
  63171. // Base texture
  63172. newTexture.hasAlpha = this.hasAlpha;
  63173. newTexture.level = this.level;
  63174. // RenderTarget Texture
  63175. newTexture.coordinatesMode = this.coordinatesMode;
  63176. if (this.renderList) {
  63177. newTexture.renderList = this.renderList.slice(0);
  63178. }
  63179. return newTexture;
  63180. };
  63181. RenderTargetTexture.prototype.serialize = function () {
  63182. if (!this.name) {
  63183. return null;
  63184. }
  63185. var serializationObject = _super.prototype.serialize.call(this);
  63186. serializationObject.renderTargetSize = this.getRenderSize();
  63187. serializationObject.renderList = [];
  63188. if (this.renderList) {
  63189. for (var index = 0; index < this.renderList.length; index++) {
  63190. serializationObject.renderList.push(this.renderList[index].id);
  63191. }
  63192. }
  63193. return serializationObject;
  63194. };
  63195. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63196. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63197. var objBuffer = this.getInternalTexture();
  63198. var scene = this.getScene();
  63199. if (objBuffer && scene) {
  63200. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63201. }
  63202. };
  63203. RenderTargetTexture.prototype.dispose = function () {
  63204. if (this._postProcessManager) {
  63205. this._postProcessManager.dispose();
  63206. this._postProcessManager = null;
  63207. }
  63208. this.clearPostProcesses(true);
  63209. if (this._resizeObserver) {
  63210. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63211. this._resizeObserver = null;
  63212. }
  63213. this.renderList = null;
  63214. // Remove from custom render targets
  63215. var scene = this.getScene();
  63216. if (!scene) {
  63217. return;
  63218. }
  63219. var index = scene.customRenderTargets.indexOf(this);
  63220. if (index >= 0) {
  63221. scene.customRenderTargets.splice(index, 1);
  63222. }
  63223. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63224. var camera = _a[_i];
  63225. index = camera.customRenderTargets.indexOf(this);
  63226. if (index >= 0) {
  63227. camera.customRenderTargets.splice(index, 1);
  63228. }
  63229. }
  63230. _super.prototype.dispose.call(this);
  63231. };
  63232. RenderTargetTexture.prototype._rebuild = function () {
  63233. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63234. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63235. }
  63236. if (this._postProcessManager) {
  63237. this._postProcessManager._rebuild();
  63238. }
  63239. };
  63240. /**
  63241. * Clear the info related to rendering groups preventing retention point in material dispose.
  63242. */
  63243. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63244. if (this._renderingManager) {
  63245. this._renderingManager.freeRenderingGroups();
  63246. }
  63247. };
  63248. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63249. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63250. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63251. return RenderTargetTexture;
  63252. }(BABYLON.Texture));
  63253. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63254. })(BABYLON || (BABYLON = {}));
  63255. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63256. var BABYLON;
  63257. (function (BABYLON) {
  63258. ;
  63259. var MultiRenderTarget = /** @class */ (function (_super) {
  63260. __extends(MultiRenderTarget, _super);
  63261. function MultiRenderTarget(name, size, count, scene, options) {
  63262. var _this = this;
  63263. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63264. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63265. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63266. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63267. _this._engine = scene.getEngine();
  63268. if (!_this.isSupported) {
  63269. _this.dispose();
  63270. return;
  63271. }
  63272. var types = [];
  63273. var samplingModes = [];
  63274. for (var i = 0; i < count; i++) {
  63275. if (options && options.types && options.types[i] !== undefined) {
  63276. types.push(options.types[i]);
  63277. }
  63278. else {
  63279. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63280. }
  63281. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63282. samplingModes.push(options.samplingModes[i]);
  63283. }
  63284. else {
  63285. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63286. }
  63287. }
  63288. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63289. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63290. _this._size = size;
  63291. _this._multiRenderTargetOptions = {
  63292. samplingModes: samplingModes,
  63293. generateMipMaps: generateMipMaps,
  63294. generateDepthBuffer: generateDepthBuffer,
  63295. generateStencilBuffer: generateStencilBuffer,
  63296. generateDepthTexture: generateDepthTexture,
  63297. types: types,
  63298. textureCount: count
  63299. };
  63300. _this._createInternalTextures();
  63301. _this._createTextures();
  63302. return _this;
  63303. }
  63304. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63305. get: function () {
  63306. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63307. },
  63308. enumerable: true,
  63309. configurable: true
  63310. });
  63311. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63312. get: function () {
  63313. return this._textures;
  63314. },
  63315. enumerable: true,
  63316. configurable: true
  63317. });
  63318. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63319. get: function () {
  63320. return this._textures[this._textures.length - 1];
  63321. },
  63322. enumerable: true,
  63323. configurable: true
  63324. });
  63325. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63326. set: function (wrap) {
  63327. if (this._textures) {
  63328. for (var i = 0; i < this._textures.length; i++) {
  63329. this._textures[i].wrapU = wrap;
  63330. }
  63331. }
  63332. },
  63333. enumerable: true,
  63334. configurable: true
  63335. });
  63336. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63337. set: function (wrap) {
  63338. if (this._textures) {
  63339. for (var i = 0; i < this._textures.length; i++) {
  63340. this._textures[i].wrapV = wrap;
  63341. }
  63342. }
  63343. },
  63344. enumerable: true,
  63345. configurable: true
  63346. });
  63347. MultiRenderTarget.prototype._rebuild = function () {
  63348. this.releaseInternalTextures();
  63349. this._createInternalTextures();
  63350. for (var i = 0; i < this._internalTextures.length; i++) {
  63351. var texture = this._textures[i];
  63352. texture._texture = this._internalTextures[i];
  63353. }
  63354. // Keeps references to frame buffer and stencil/depth buffer
  63355. this._texture = this._internalTextures[0];
  63356. };
  63357. MultiRenderTarget.prototype._createInternalTextures = function () {
  63358. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63359. };
  63360. MultiRenderTarget.prototype._createTextures = function () {
  63361. this._textures = [];
  63362. for (var i = 0; i < this._internalTextures.length; i++) {
  63363. var texture = new BABYLON.Texture(null, this.getScene());
  63364. texture._texture = this._internalTextures[i];
  63365. this._textures.push(texture);
  63366. }
  63367. // Keeps references to frame buffer and stencil/depth buffer
  63368. this._texture = this._internalTextures[0];
  63369. };
  63370. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63371. get: function () {
  63372. return this._samples;
  63373. },
  63374. set: function (value) {
  63375. if (this._samples === value) {
  63376. return;
  63377. }
  63378. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63379. },
  63380. enumerable: true,
  63381. configurable: true
  63382. });
  63383. MultiRenderTarget.prototype.resize = function (size) {
  63384. this.releaseInternalTextures();
  63385. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63386. this._createInternalTextures();
  63387. };
  63388. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63389. var _this = this;
  63390. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63391. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63392. });
  63393. };
  63394. MultiRenderTarget.prototype.dispose = function () {
  63395. this.releaseInternalTextures();
  63396. _super.prototype.dispose.call(this);
  63397. };
  63398. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63399. if (!this._internalTextures) {
  63400. return;
  63401. }
  63402. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63403. if (this._internalTextures[i] !== undefined) {
  63404. this._internalTextures[i].dispose();
  63405. this._internalTextures.splice(i, 1);
  63406. }
  63407. }
  63408. };
  63409. return MultiRenderTarget;
  63410. }(BABYLON.RenderTargetTexture));
  63411. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63412. })(BABYLON || (BABYLON = {}));
  63413. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63414. var BABYLON;
  63415. (function (BABYLON) {
  63416. var MirrorTexture = /** @class */ (function (_super) {
  63417. __extends(MirrorTexture, _super);
  63418. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63419. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63421. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63422. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63423. _this.scene = scene;
  63424. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63425. _this._transformMatrix = BABYLON.Matrix.Zero();
  63426. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63427. _this._adaptiveBlurKernel = 0;
  63428. _this._blurKernelX = 0;
  63429. _this._blurKernelY = 0;
  63430. _this._blurRatio = 1.0;
  63431. _this.ignoreCameraViewport = true;
  63432. _this._updateGammaSpace();
  63433. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63434. _this._updateGammaSpace;
  63435. });
  63436. _this.onBeforeRenderObservable.add(function () {
  63437. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63438. _this._savedViewMatrix = scene.getViewMatrix();
  63439. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63440. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63441. scene.clipPlane = _this.mirrorPlane;
  63442. scene.getEngine().cullBackFaces = false;
  63443. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63444. });
  63445. _this.onAfterRenderObservable.add(function () {
  63446. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63447. scene.getEngine().cullBackFaces = true;
  63448. scene._mirroredCameraPosition = null;
  63449. delete scene.clipPlane;
  63450. });
  63451. return _this;
  63452. }
  63453. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63454. get: function () {
  63455. return this._blurRatio;
  63456. },
  63457. set: function (value) {
  63458. if (this._blurRatio === value) {
  63459. return;
  63460. }
  63461. this._blurRatio = value;
  63462. this._preparePostProcesses();
  63463. },
  63464. enumerable: true,
  63465. configurable: true
  63466. });
  63467. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63468. set: function (value) {
  63469. this._adaptiveBlurKernel = value;
  63470. this._autoComputeBlurKernel();
  63471. },
  63472. enumerable: true,
  63473. configurable: true
  63474. });
  63475. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63476. set: function (value) {
  63477. this.blurKernelX = value;
  63478. this.blurKernelY = value;
  63479. },
  63480. enumerable: true,
  63481. configurable: true
  63482. });
  63483. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63484. get: function () {
  63485. return this._blurKernelX;
  63486. },
  63487. set: function (value) {
  63488. if (this._blurKernelX === value) {
  63489. return;
  63490. }
  63491. this._blurKernelX = value;
  63492. this._preparePostProcesses();
  63493. },
  63494. enumerable: true,
  63495. configurable: true
  63496. });
  63497. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63498. get: function () {
  63499. return this._blurKernelY;
  63500. },
  63501. set: function (value) {
  63502. if (this._blurKernelY === value) {
  63503. return;
  63504. }
  63505. this._blurKernelY = value;
  63506. this._preparePostProcesses();
  63507. },
  63508. enumerable: true,
  63509. configurable: true
  63510. });
  63511. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63512. var engine = this.getScene().getEngine();
  63513. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63514. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63515. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63516. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63517. };
  63518. MirrorTexture.prototype._onRatioRescale = function () {
  63519. if (this._sizeRatio) {
  63520. this.resize(this._initialSizeParameter);
  63521. if (!this._adaptiveBlurKernel) {
  63522. this._preparePostProcesses();
  63523. }
  63524. }
  63525. if (this._adaptiveBlurKernel) {
  63526. this._autoComputeBlurKernel();
  63527. }
  63528. };
  63529. MirrorTexture.prototype._updateGammaSpace = function () {
  63530. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63531. };
  63532. MirrorTexture.prototype._preparePostProcesses = function () {
  63533. this.clearPostProcesses(true);
  63534. if (this._blurKernelX && this._blurKernelY) {
  63535. var engine = this.getScene().getEngine();
  63536. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63537. 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);
  63538. this._blurX.autoClear = false;
  63539. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63540. this._blurX.inputTexture = this._texture;
  63541. }
  63542. else {
  63543. this._blurX.alwaysForcePOT = true;
  63544. }
  63545. 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);
  63546. this._blurY.autoClear = false;
  63547. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63548. this.addPostProcess(this._blurX);
  63549. this.addPostProcess(this._blurY);
  63550. }
  63551. else {
  63552. if (this._blurY) {
  63553. this.removePostProcess(this._blurY);
  63554. this._blurY.dispose();
  63555. this._blurY = null;
  63556. }
  63557. if (this._blurX) {
  63558. this.removePostProcess(this._blurX);
  63559. this._blurX.dispose();
  63560. this._blurX = null;
  63561. }
  63562. }
  63563. };
  63564. MirrorTexture.prototype.clone = function () {
  63565. var scene = this.getScene();
  63566. if (!scene) {
  63567. return this;
  63568. }
  63569. var textureSize = this.getSize();
  63570. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63571. // Base texture
  63572. newTexture.hasAlpha = this.hasAlpha;
  63573. newTexture.level = this.level;
  63574. // Mirror Texture
  63575. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63576. if (this.renderList) {
  63577. newTexture.renderList = this.renderList.slice(0);
  63578. }
  63579. return newTexture;
  63580. };
  63581. MirrorTexture.prototype.serialize = function () {
  63582. if (!this.name) {
  63583. return null;
  63584. }
  63585. var serializationObject = _super.prototype.serialize.call(this);
  63586. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63587. return serializationObject;
  63588. };
  63589. MirrorTexture.prototype.dispose = function () {
  63590. _super.prototype.dispose.call(this);
  63591. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63592. };
  63593. return MirrorTexture;
  63594. }(BABYLON.RenderTargetTexture));
  63595. BABYLON.MirrorTexture = MirrorTexture;
  63596. })(BABYLON || (BABYLON = {}));
  63597. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63598. var BABYLON;
  63599. (function (BABYLON) {
  63600. /**
  63601. * Creates a refraction texture used by refraction channel of the standard material.
  63602. * @param name the texture name
  63603. * @param size size of the underlying texture
  63604. * @param scene root scene
  63605. */
  63606. var RefractionTexture = /** @class */ (function (_super) {
  63607. __extends(RefractionTexture, _super);
  63608. function RefractionTexture(name, size, scene, generateMipMaps) {
  63609. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63610. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63611. _this.depth = 2.0;
  63612. _this.onBeforeRenderObservable.add(function () {
  63613. scene.clipPlane = _this.refractionPlane;
  63614. });
  63615. _this.onAfterRenderObservable.add(function () {
  63616. delete scene.clipPlane;
  63617. });
  63618. return _this;
  63619. }
  63620. RefractionTexture.prototype.clone = function () {
  63621. var scene = this.getScene();
  63622. if (!scene) {
  63623. return this;
  63624. }
  63625. var textureSize = this.getSize();
  63626. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63627. // Base texture
  63628. newTexture.hasAlpha = this.hasAlpha;
  63629. newTexture.level = this.level;
  63630. // Refraction Texture
  63631. newTexture.refractionPlane = this.refractionPlane.clone();
  63632. if (this.renderList) {
  63633. newTexture.renderList = this.renderList.slice(0);
  63634. }
  63635. newTexture.depth = this.depth;
  63636. return newTexture;
  63637. };
  63638. RefractionTexture.prototype.serialize = function () {
  63639. if (!this.name) {
  63640. return null;
  63641. }
  63642. var serializationObject = _super.prototype.serialize.call(this);
  63643. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63644. serializationObject.depth = this.depth;
  63645. return serializationObject;
  63646. };
  63647. return RefractionTexture;
  63648. }(BABYLON.RenderTargetTexture));
  63649. BABYLON.RefractionTexture = RefractionTexture;
  63650. })(BABYLON || (BABYLON = {}));
  63651. //# sourceMappingURL=babylon.refractionTexture.js.map
  63652. var BABYLON;
  63653. (function (BABYLON) {
  63654. /**
  63655. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63656. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63657. */
  63658. var DynamicTexture = /** @class */ (function (_super) {
  63659. __extends(DynamicTexture, _super);
  63660. /**
  63661. * Creates a {BABYLON.DynamicTexture}
  63662. * @param name defines the name of the texture
  63663. * @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
  63664. * @param scene defines the scene where you want the texture
  63665. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63666. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63667. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63668. */
  63669. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63670. if (scene === void 0) { scene = null; }
  63671. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63672. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63673. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63674. _this.name = name;
  63675. _this._engine = _this.getScene().getEngine();
  63676. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63677. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63678. _this._generateMipMaps = generateMipMaps;
  63679. if (options.getContext) {
  63680. _this._canvas = options;
  63681. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63682. }
  63683. else {
  63684. _this._canvas = document.createElement("canvas");
  63685. if (options.width) {
  63686. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63687. }
  63688. else {
  63689. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63690. }
  63691. }
  63692. var textureSize = _this.getSize();
  63693. _this._canvas.width = textureSize.width;
  63694. _this._canvas.height = textureSize.height;
  63695. _this._context = _this._canvas.getContext("2d");
  63696. return _this;
  63697. }
  63698. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63699. /**
  63700. * Gets the current state of canRescale
  63701. */
  63702. get: function () {
  63703. return true;
  63704. },
  63705. enumerable: true,
  63706. configurable: true
  63707. });
  63708. DynamicTexture.prototype._recreate = function (textureSize) {
  63709. this._canvas.width = textureSize.width;
  63710. this._canvas.height = textureSize.height;
  63711. this.releaseInternalTexture();
  63712. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63713. };
  63714. /**
  63715. * Scales the texture
  63716. * @param ratio the scale factor to apply to both width and height
  63717. */
  63718. DynamicTexture.prototype.scale = function (ratio) {
  63719. var textureSize = this.getSize();
  63720. textureSize.width *= ratio;
  63721. textureSize.height *= ratio;
  63722. this._recreate(textureSize);
  63723. };
  63724. /**
  63725. * Resizes the texture
  63726. * @param width the new width
  63727. * @param height the new height
  63728. */
  63729. DynamicTexture.prototype.scaleTo = function (width, height) {
  63730. var textureSize = this.getSize();
  63731. textureSize.width = width;
  63732. textureSize.height = height;
  63733. this._recreate(textureSize);
  63734. };
  63735. /**
  63736. * Gets the context of the canvas used by the texture
  63737. * @returns the canvas context of the dynamic texture
  63738. */
  63739. DynamicTexture.prototype.getContext = function () {
  63740. return this._context;
  63741. };
  63742. /**
  63743. * Clears the texture
  63744. */
  63745. DynamicTexture.prototype.clear = function () {
  63746. var size = this.getSize();
  63747. this._context.fillRect(0, 0, size.width, size.height);
  63748. };
  63749. /**
  63750. * Updates the texture
  63751. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63752. */
  63753. DynamicTexture.prototype.update = function (invertY) {
  63754. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63755. };
  63756. /**
  63757. * Draws text onto the texture
  63758. * @param text defines the text to be drawn
  63759. * @param x defines the placement of the text from the left
  63760. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63761. * @param font defines the font to be used with font-style, font-size, font-name
  63762. * @param color defines the color used for the text
  63763. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63764. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63765. * @param update defines whether texture is immediately update (default is true)
  63766. */
  63767. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63768. if (update === void 0) { update = true; }
  63769. var size = this.getSize();
  63770. if (clearColor) {
  63771. this._context.fillStyle = clearColor;
  63772. this._context.fillRect(0, 0, size.width, size.height);
  63773. }
  63774. this._context.font = font;
  63775. if (x === null || x === undefined) {
  63776. var textSize = this._context.measureText(text);
  63777. x = (size.width - textSize.width) / 2;
  63778. }
  63779. if (y === null || y === undefined) {
  63780. var fontSize = parseInt((font.replace(/\D/g, '')));
  63781. ;
  63782. y = (size.height / 2) + (fontSize / 3.65);
  63783. }
  63784. this._context.fillStyle = color;
  63785. this._context.fillText(text, x, y);
  63786. if (update) {
  63787. this.update(invertY);
  63788. }
  63789. };
  63790. /**
  63791. * Clones the texture
  63792. * @returns the clone of the texture.
  63793. */
  63794. DynamicTexture.prototype.clone = function () {
  63795. var scene = this.getScene();
  63796. if (!scene) {
  63797. return this;
  63798. }
  63799. var textureSize = this.getSize();
  63800. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63801. // Base texture
  63802. newTexture.hasAlpha = this.hasAlpha;
  63803. newTexture.level = this.level;
  63804. // Dynamic Texture
  63805. newTexture.wrapU = this.wrapU;
  63806. newTexture.wrapV = this.wrapV;
  63807. return newTexture;
  63808. };
  63809. /** @ignore */
  63810. DynamicTexture.prototype._rebuild = function () {
  63811. this.update();
  63812. };
  63813. return DynamicTexture;
  63814. }(BABYLON.Texture));
  63815. BABYLON.DynamicTexture = DynamicTexture;
  63816. })(BABYLON || (BABYLON = {}));
  63817. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63818. var BABYLON;
  63819. (function (BABYLON) {
  63820. var VideoTexture = /** @class */ (function (_super) {
  63821. __extends(VideoTexture, _super);
  63822. /**
  63823. * Creates a video texture.
  63824. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63825. * @param {string | null} name optional name, will detect from video source, if not defined
  63826. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63827. * @param {BABYLON.Scene} scene is obviously the current scene.
  63828. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63829. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63830. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63831. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63832. */
  63833. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63834. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63835. if (invertY === void 0) { invertY = false; }
  63836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63837. if (settings === void 0) { settings = {
  63838. autoPlay: true,
  63839. loop: true,
  63840. autoUpdateTexture: true,
  63841. }; }
  63842. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63843. _this._createInternalTexture = function () {
  63844. if (_this._texture != null) {
  63845. return;
  63846. }
  63847. if (!_this._engine.needPOTTextures ||
  63848. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63849. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63850. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63851. }
  63852. else {
  63853. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63854. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63855. _this._generateMipMaps = false;
  63856. }
  63857. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63858. _this._texture.isReady = true;
  63859. _this._updateInternalTexture();
  63860. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63861. _this.onLoadObservable.notifyObservers(_this);
  63862. }
  63863. };
  63864. _this.reset = function () {
  63865. if (_this._texture == null) {
  63866. return;
  63867. }
  63868. _this._texture.dispose();
  63869. _this._texture = null;
  63870. };
  63871. _this._updateInternalTexture = function (e) {
  63872. if (_this._texture == null || !_this._texture.isReady) {
  63873. return;
  63874. }
  63875. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63876. return;
  63877. }
  63878. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63879. };
  63880. _this._engine = _this.getScene().getEngine();
  63881. _this._generateMipMaps = generateMipMaps;
  63882. _this._samplingMode = samplingMode;
  63883. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63884. _this.name = name || _this._getName(src);
  63885. _this.video = _this._getVideo(src);
  63886. if (settings.autoPlay !== undefined) {
  63887. _this.video.autoplay = settings.autoPlay;
  63888. }
  63889. if (settings.loop !== undefined) {
  63890. _this.video.loop = settings.loop;
  63891. }
  63892. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63893. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63894. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63895. _this.video.addEventListener("emptied", _this.reset);
  63896. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63897. _this._createInternalTexture();
  63898. }
  63899. return _this;
  63900. }
  63901. VideoTexture.prototype._getName = function (src) {
  63902. if (src instanceof HTMLVideoElement) {
  63903. return src.currentSrc;
  63904. }
  63905. if (typeof src === "object") {
  63906. return src.toString();
  63907. }
  63908. return src;
  63909. };
  63910. ;
  63911. VideoTexture.prototype._getVideo = function (src) {
  63912. if (src instanceof HTMLVideoElement) {
  63913. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63914. return src;
  63915. }
  63916. var video = document.createElement("video");
  63917. if (typeof src === "string") {
  63918. BABYLON.Tools.SetCorsBehavior(src, video);
  63919. video.src = src;
  63920. }
  63921. else {
  63922. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63923. src.forEach(function (url) {
  63924. var source = document.createElement("source");
  63925. source.src = url;
  63926. video.appendChild(source);
  63927. });
  63928. }
  63929. return video;
  63930. };
  63931. ;
  63932. /**
  63933. * Internal method to initiate `update`.
  63934. */
  63935. VideoTexture.prototype._rebuild = function () {
  63936. this.update();
  63937. };
  63938. /**
  63939. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63940. */
  63941. VideoTexture.prototype.update = function () {
  63942. if (!this.autoUpdateTexture) {
  63943. // Expecting user to call `updateTexture` manually
  63944. return;
  63945. }
  63946. this.updateTexture(true);
  63947. };
  63948. /**
  63949. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  63950. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  63951. */
  63952. VideoTexture.prototype.updateTexture = function (isVisible) {
  63953. if (!isVisible) {
  63954. return;
  63955. }
  63956. if (this.video.paused) {
  63957. return;
  63958. }
  63959. this._updateInternalTexture();
  63960. };
  63961. /**
  63962. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  63963. * @param url New url.
  63964. */
  63965. VideoTexture.prototype.updateURL = function (url) {
  63966. this.video.src = url;
  63967. };
  63968. VideoTexture.prototype.dispose = function () {
  63969. _super.prototype.dispose.call(this);
  63970. this.video.removeEventListener("canplay", this._createInternalTexture);
  63971. this.video.removeEventListener("paused", this._updateInternalTexture);
  63972. this.video.removeEventListener("seeked", this._updateInternalTexture);
  63973. this.video.removeEventListener("emptied", this.reset);
  63974. this.video.pause();
  63975. };
  63976. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  63977. var video = document.createElement("video");
  63978. var constraintsDeviceId;
  63979. if (constraints && constraints.deviceId) {
  63980. constraintsDeviceId = {
  63981. exact: constraints.deviceId,
  63982. };
  63983. }
  63984. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  63985. if (navigator.mediaDevices) {
  63986. navigator.mediaDevices.getUserMedia({ video: constraints })
  63987. .then(function (stream) {
  63988. if (video.mozSrcObject !== undefined) {
  63989. // hack for Firefox < 19
  63990. video.mozSrcObject = stream;
  63991. }
  63992. else {
  63993. video.srcObject = stream;
  63994. }
  63995. var onPlaying = function () {
  63996. if (onReady) {
  63997. onReady(new VideoTexture("video", video, scene, true, true));
  63998. }
  63999. video.removeEventListener("playing", onPlaying);
  64000. };
  64001. video.addEventListener("playing", onPlaying);
  64002. video.play();
  64003. })
  64004. .catch(function (err) {
  64005. BABYLON.Tools.Error(err.name);
  64006. });
  64007. }
  64008. else {
  64009. navigator.getUserMedia =
  64010. navigator.getUserMedia ||
  64011. navigator.webkitGetUserMedia ||
  64012. navigator.mozGetUserMedia ||
  64013. navigator.msGetUserMedia;
  64014. if (navigator.getUserMedia) {
  64015. navigator.getUserMedia({
  64016. video: {
  64017. deviceId: constraintsDeviceId,
  64018. width: {
  64019. min: (constraints && constraints.minWidth) || 256,
  64020. max: (constraints && constraints.maxWidth) || 640,
  64021. },
  64022. height: {
  64023. min: (constraints && constraints.minHeight) || 256,
  64024. max: (constraints && constraints.maxHeight) || 480,
  64025. },
  64026. },
  64027. }, function (stream) {
  64028. if (video.mozSrcObject !== undefined) {
  64029. // hack for Firefox < 19
  64030. video.mozSrcObject = stream;
  64031. }
  64032. else {
  64033. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64034. }
  64035. video.play();
  64036. if (onReady) {
  64037. onReady(new VideoTexture("video", video, scene, true, true));
  64038. }
  64039. }, function (e) {
  64040. BABYLON.Tools.Error(e.name);
  64041. });
  64042. }
  64043. }
  64044. };
  64045. return VideoTexture;
  64046. }(BABYLON.Texture));
  64047. BABYLON.VideoTexture = VideoTexture;
  64048. })(BABYLON || (BABYLON = {}));
  64049. //# sourceMappingURL=babylon.videoTexture.js.map
  64050. var BABYLON;
  64051. (function (BABYLON) {
  64052. var RawTexture = /** @class */ (function (_super) {
  64053. __extends(RawTexture, _super);
  64054. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64055. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64056. if (invertY === void 0) { invertY = false; }
  64057. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64058. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64059. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64060. _this.format = format;
  64061. _this._engine = scene.getEngine();
  64062. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64063. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64064. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64065. return _this;
  64066. }
  64067. RawTexture.prototype.update = function (data) {
  64068. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64069. };
  64070. // Statics
  64071. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64072. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64073. if (invertY === void 0) { invertY = false; }
  64074. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64075. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64076. };
  64077. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64078. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64079. if (invertY === void 0) { invertY = false; }
  64080. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64081. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64082. };
  64083. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64084. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64085. if (invertY === void 0) { invertY = false; }
  64086. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64087. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64088. };
  64089. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64090. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64091. if (invertY === void 0) { invertY = false; }
  64092. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64093. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64094. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64095. };
  64096. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64097. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64098. if (invertY === void 0) { invertY = false; }
  64099. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64100. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64101. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64102. };
  64103. return RawTexture;
  64104. }(BABYLON.Texture));
  64105. BABYLON.RawTexture = RawTexture;
  64106. })(BABYLON || (BABYLON = {}));
  64107. //# sourceMappingURL=babylon.rawTexture.js.map
  64108. var BABYLON;
  64109. (function (BABYLON) {
  64110. /**
  64111. * Class used to store 3D textures containing user data
  64112. */
  64113. var RawTexture3D = /** @class */ (function (_super) {
  64114. __extends(RawTexture3D, _super);
  64115. /**
  64116. * Create a new RawTexture3D
  64117. * @param data defines the data of the texture
  64118. * @param width defines the width of the texture
  64119. * @param height defines the height of the texture
  64120. * @param depth defines the depth of the texture
  64121. * @param format defines the texture format to use
  64122. * @param scene defines the hosting scene
  64123. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64124. * @param invertY defines if texture must be stored with Y axis inverted
  64125. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64126. */
  64127. function RawTexture3D(data, width, height, depth,
  64128. /** Gets or sets the texture format to use*/
  64129. format, scene, generateMipMaps, invertY, samplingMode) {
  64130. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64131. if (invertY === void 0) { invertY = false; }
  64132. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64133. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64134. _this.format = format;
  64135. _this._engine = scene.getEngine();
  64136. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64137. _this.is3D = true;
  64138. return _this;
  64139. }
  64140. /**
  64141. * Update the texture with new data
  64142. * @param data defines the data to store in the texture
  64143. */
  64144. RawTexture3D.prototype.update = function (data) {
  64145. if (!this._texture) {
  64146. return;
  64147. }
  64148. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64149. };
  64150. return RawTexture3D;
  64151. }(BABYLON.Texture));
  64152. BABYLON.RawTexture3D = RawTexture3D;
  64153. })(BABYLON || (BABYLON = {}));
  64154. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64155. var BABYLON;
  64156. (function (BABYLON) {
  64157. /**
  64158. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64159. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64160. */
  64161. var PostProcess = /** @class */ (function () {
  64162. /**
  64163. * Creates a new instance PostProcess
  64164. * @param name The name of the PostProcess.
  64165. * @param fragmentUrl The url of the fragment shader to be used.
  64166. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64167. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64168. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64169. * @param camera The camera to apply the render pass to.
  64170. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64171. * @param engine The engine which the post process will be applied. (default: current engine)
  64172. * @param reusable If the post process can be reused on the same frame. (default: false)
  64173. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64174. * @param textureType Type of textures used when performing the post process. (default: 0)
  64175. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64176. * @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
  64177. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64178. */
  64179. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64181. if (defines === void 0) { defines = null; }
  64182. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64183. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64184. if (blockCompilation === void 0) { blockCompilation = false; }
  64185. this.name = name;
  64186. /**
  64187. * Width of the texture to apply the post process on
  64188. */
  64189. this.width = -1;
  64190. /**
  64191. * Height of the texture to apply the post process on
  64192. */
  64193. this.height = -1;
  64194. /**
  64195. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64196. */
  64197. this._outputTexture = null;
  64198. /**
  64199. * If the buffer needs to be cleared before applying the post process. (default: true)
  64200. * Should be set to false if shader will overwrite all previous pixels.
  64201. */
  64202. this.autoClear = true;
  64203. /**
  64204. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64205. */
  64206. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64207. /**
  64208. * Animations to be used for the post processing
  64209. */
  64210. this.animations = new Array();
  64211. /**
  64212. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64213. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64214. */
  64215. this.enablePixelPerfectMode = false;
  64216. /**
  64217. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64218. */
  64219. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64220. /**
  64221. * Force textures to be a power of two (default: false)
  64222. */
  64223. this.alwaysForcePOT = false;
  64224. /**
  64225. * Number of sample textures (default: 1)
  64226. */
  64227. this.samples = 1;
  64228. /**
  64229. * Modify the scale of the post process to be the same as the viewport (default: false)
  64230. */
  64231. this.adaptScaleToCurrentViewport = false;
  64232. this._reusable = false;
  64233. /**
  64234. * Smart array of input and output textures for the post process.
  64235. */
  64236. this._textures = new BABYLON.SmartArray(2);
  64237. /**
  64238. * The index in _textures that corresponds to the output texture.
  64239. */
  64240. this._currentRenderTextureInd = 0;
  64241. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64242. this._texelSize = BABYLON.Vector2.Zero();
  64243. // Events
  64244. /**
  64245. * An event triggered when the postprocess is activated.
  64246. */
  64247. this.onActivateObservable = new BABYLON.Observable();
  64248. /**
  64249. * An event triggered when the postprocess changes its size.
  64250. */
  64251. this.onSizeChangedObservable = new BABYLON.Observable();
  64252. /**
  64253. * An event triggered when the postprocess applies its effect.
  64254. */
  64255. this.onApplyObservable = new BABYLON.Observable();
  64256. /**
  64257. * An event triggered before rendering the postprocess
  64258. */
  64259. this.onBeforeRenderObservable = new BABYLON.Observable();
  64260. /**
  64261. * An event triggered after rendering the postprocess
  64262. */
  64263. this.onAfterRenderObservable = new BABYLON.Observable();
  64264. if (camera != null) {
  64265. this._camera = camera;
  64266. this._scene = camera.getScene();
  64267. camera.attachPostProcess(this);
  64268. this._engine = this._scene.getEngine();
  64269. this._scene.postProcesses.push(this);
  64270. }
  64271. else if (engine) {
  64272. this._engine = engine;
  64273. this._engine.postProcesses.push(this);
  64274. }
  64275. this._options = options;
  64276. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64277. this._reusable = reusable || false;
  64278. this._textureType = textureType;
  64279. this._samplers = samplers || [];
  64280. this._samplers.push("textureSampler");
  64281. this._fragmentUrl = fragmentUrl;
  64282. this._vertexUrl = vertexUrl;
  64283. this._parameters = parameters || [];
  64284. this._parameters.push("scale");
  64285. this._indexParameters = indexParameters;
  64286. if (!blockCompilation) {
  64287. this.updateEffect(defines);
  64288. }
  64289. }
  64290. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64291. /**
  64292. * A function that is added to the onActivateObservable
  64293. */
  64294. set: function (callback) {
  64295. if (this._onActivateObserver) {
  64296. this.onActivateObservable.remove(this._onActivateObserver);
  64297. }
  64298. if (callback) {
  64299. this._onActivateObserver = this.onActivateObservable.add(callback);
  64300. }
  64301. },
  64302. enumerable: true,
  64303. configurable: true
  64304. });
  64305. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64306. /**
  64307. * A function that is added to the onSizeChangedObservable
  64308. */
  64309. set: function (callback) {
  64310. if (this._onSizeChangedObserver) {
  64311. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64312. }
  64313. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64314. },
  64315. enumerable: true,
  64316. configurable: true
  64317. });
  64318. Object.defineProperty(PostProcess.prototype, "onApply", {
  64319. /**
  64320. * A function that is added to the onApplyObservable
  64321. */
  64322. set: function (callback) {
  64323. if (this._onApplyObserver) {
  64324. this.onApplyObservable.remove(this._onApplyObserver);
  64325. }
  64326. this._onApplyObserver = this.onApplyObservable.add(callback);
  64327. },
  64328. enumerable: true,
  64329. configurable: true
  64330. });
  64331. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64332. /**
  64333. * A function that is added to the onBeforeRenderObservable
  64334. */
  64335. set: function (callback) {
  64336. if (this._onBeforeRenderObserver) {
  64337. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64338. }
  64339. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64340. },
  64341. enumerable: true,
  64342. configurable: true
  64343. });
  64344. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64345. /**
  64346. * A function that is added to the onAfterRenderObservable
  64347. */
  64348. set: function (callback) {
  64349. if (this._onAfterRenderObserver) {
  64350. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64351. }
  64352. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64353. },
  64354. enumerable: true,
  64355. configurable: true
  64356. });
  64357. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64358. /**
  64359. * 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
  64360. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64361. */
  64362. get: function () {
  64363. return this._textures.data[this._currentRenderTextureInd];
  64364. },
  64365. set: function (value) {
  64366. this._forcedOutputTexture = value;
  64367. },
  64368. enumerable: true,
  64369. configurable: true
  64370. });
  64371. /**
  64372. * Gets the camera which post process is applied to.
  64373. * @returns The camera the post process is applied to.
  64374. */
  64375. PostProcess.prototype.getCamera = function () {
  64376. return this._camera;
  64377. };
  64378. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64379. /**
  64380. * Gets the texel size of the postprocess.
  64381. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64382. */
  64383. get: function () {
  64384. if (this._shareOutputWithPostProcess) {
  64385. return this._shareOutputWithPostProcess.texelSize;
  64386. }
  64387. if (this._forcedOutputTexture) {
  64388. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64389. }
  64390. return this._texelSize;
  64391. },
  64392. enumerable: true,
  64393. configurable: true
  64394. });
  64395. /**
  64396. * Gets the engine which this post process belongs to.
  64397. * @returns The engine the post process was enabled with.
  64398. */
  64399. PostProcess.prototype.getEngine = function () {
  64400. return this._engine;
  64401. };
  64402. /**
  64403. * The effect that is created when initializing the post process.
  64404. * @returns The created effect corrisponding the the postprocess.
  64405. */
  64406. PostProcess.prototype.getEffect = function () {
  64407. return this._effect;
  64408. };
  64409. /**
  64410. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64411. * @param postProcess The post process to share the output with.
  64412. * @returns This post process.
  64413. */
  64414. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64415. this._disposeTextures();
  64416. this._shareOutputWithPostProcess = postProcess;
  64417. return this;
  64418. };
  64419. /**
  64420. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64421. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64422. */
  64423. PostProcess.prototype.useOwnOutput = function () {
  64424. if (this._textures.length == 0) {
  64425. this._textures = new BABYLON.SmartArray(2);
  64426. }
  64427. this._shareOutputWithPostProcess = null;
  64428. };
  64429. /**
  64430. * Updates the effect with the current post process compile time values and recompiles the shader.
  64431. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64432. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64433. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64434. * @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
  64435. * @param onCompiled Called when the shader has been compiled.
  64436. * @param onError Called if there is an error when compiling a shader.
  64437. */
  64438. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64439. if (defines === void 0) { defines = null; }
  64440. if (uniforms === void 0) { uniforms = null; }
  64441. if (samplers === void 0) { samplers = null; }
  64442. 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);
  64443. };
  64444. /**
  64445. * The post process is reusable if it can be used multiple times within one frame.
  64446. * @returns If the post process is reusable
  64447. */
  64448. PostProcess.prototype.isReusable = function () {
  64449. return this._reusable;
  64450. };
  64451. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64452. PostProcess.prototype.markTextureDirty = function () {
  64453. this.width = -1;
  64454. };
  64455. /**
  64456. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64457. * 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.
  64458. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64459. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64460. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64461. * @returns The target texture that was bound to be written to.
  64462. */
  64463. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64464. var _this = this;
  64465. if (sourceTexture === void 0) { sourceTexture = null; }
  64466. camera = camera || this._camera;
  64467. var scene = camera.getScene();
  64468. var engine = scene.getEngine();
  64469. var maxSize = engine.getCaps().maxTextureSize;
  64470. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64471. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64472. // 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
  64473. var webVRCamera = camera.parent;
  64474. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64475. requiredWidth /= 2;
  64476. }
  64477. var desiredWidth = (this._options.width || requiredWidth);
  64478. var desiredHeight = this._options.height || requiredHeight;
  64479. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64480. if (this.adaptScaleToCurrentViewport) {
  64481. var currentViewport = engine.currentViewport;
  64482. if (currentViewport) {
  64483. desiredWidth *= currentViewport.width;
  64484. desiredHeight *= currentViewport.height;
  64485. }
  64486. }
  64487. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64488. if (!this._options.width) {
  64489. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64490. }
  64491. if (!this._options.height) {
  64492. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64493. }
  64494. }
  64495. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64496. if (this._textures.length > 0) {
  64497. for (var i = 0; i < this._textures.length; i++) {
  64498. this._engine._releaseTexture(this._textures.data[i]);
  64499. }
  64500. this._textures.reset();
  64501. }
  64502. this.width = desiredWidth;
  64503. this.height = desiredHeight;
  64504. var textureSize = { width: this.width, height: this.height };
  64505. var textureOptions = {
  64506. generateMipMaps: false,
  64507. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64508. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64509. samplingMode: this.renderTargetSamplingMode,
  64510. type: this._textureType
  64511. };
  64512. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64513. if (this._reusable) {
  64514. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64515. }
  64516. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64517. this.onSizeChangedObservable.notifyObservers(this);
  64518. }
  64519. this._textures.forEach(function (texture) {
  64520. if (texture.samples !== _this.samples) {
  64521. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64522. }
  64523. });
  64524. }
  64525. var target;
  64526. if (this._shareOutputWithPostProcess) {
  64527. target = this._shareOutputWithPostProcess.inputTexture;
  64528. }
  64529. else if (this._forcedOutputTexture) {
  64530. target = this._forcedOutputTexture;
  64531. this.width = this._forcedOutputTexture.width;
  64532. this.height = this._forcedOutputTexture.height;
  64533. }
  64534. else {
  64535. target = this.inputTexture;
  64536. }
  64537. // Bind the input of this post process to be used as the output of the previous post process.
  64538. if (this.enablePixelPerfectMode) {
  64539. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64540. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64541. }
  64542. else {
  64543. this._scaleRatio.copyFromFloats(1, 1);
  64544. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64545. }
  64546. this.onActivateObservable.notifyObservers(camera);
  64547. // Clear
  64548. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64549. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64550. }
  64551. if (this._reusable) {
  64552. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64553. }
  64554. return target;
  64555. };
  64556. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64557. /**
  64558. * If the post process is supported.
  64559. */
  64560. get: function () {
  64561. return this._effect.isSupported;
  64562. },
  64563. enumerable: true,
  64564. configurable: true
  64565. });
  64566. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64567. /**
  64568. * The aspect ratio of the output texture.
  64569. */
  64570. get: function () {
  64571. if (this._shareOutputWithPostProcess) {
  64572. return this._shareOutputWithPostProcess.aspectRatio;
  64573. }
  64574. if (this._forcedOutputTexture) {
  64575. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64576. }
  64577. return this.width / this.height;
  64578. },
  64579. enumerable: true,
  64580. configurable: true
  64581. });
  64582. /**
  64583. * Get a value indicating if the post-process is ready to be used
  64584. * @returns true if the post-process is ready (shader is compiled)
  64585. */
  64586. PostProcess.prototype.isReady = function () {
  64587. return this._effect && this._effect.isReady();
  64588. };
  64589. /**
  64590. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64591. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64592. */
  64593. PostProcess.prototype.apply = function () {
  64594. // Check
  64595. if (!this._effect || !this._effect.isReady())
  64596. return null;
  64597. // States
  64598. this._engine.enableEffect(this._effect);
  64599. this._engine.setState(false);
  64600. this._engine.setDepthBuffer(false);
  64601. this._engine.setDepthWrite(false);
  64602. // Alpha
  64603. this._engine.setAlphaMode(this.alphaMode);
  64604. if (this.alphaConstants) {
  64605. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64606. }
  64607. // Bind the output texture of the preivous post process as the input to this post process.
  64608. var source;
  64609. if (this._shareOutputWithPostProcess) {
  64610. source = this._shareOutputWithPostProcess.inputTexture;
  64611. }
  64612. else if (this._forcedOutputTexture) {
  64613. source = this._forcedOutputTexture;
  64614. }
  64615. else {
  64616. source = this.inputTexture;
  64617. }
  64618. this._effect._bindTexture("textureSampler", source);
  64619. // Parameters
  64620. this._effect.setVector2("scale", this._scaleRatio);
  64621. this.onApplyObservable.notifyObservers(this._effect);
  64622. return this._effect;
  64623. };
  64624. PostProcess.prototype._disposeTextures = function () {
  64625. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64626. return;
  64627. }
  64628. if (this._textures.length > 0) {
  64629. for (var i = 0; i < this._textures.length; i++) {
  64630. this._engine._releaseTexture(this._textures.data[i]);
  64631. }
  64632. }
  64633. this._textures.dispose();
  64634. };
  64635. /**
  64636. * Disposes the post process.
  64637. * @param camera The camera to dispose the post process on.
  64638. */
  64639. PostProcess.prototype.dispose = function (camera) {
  64640. camera = camera || this._camera;
  64641. this._disposeTextures();
  64642. if (this._scene) {
  64643. var index_1 = this._scene.postProcesses.indexOf(this);
  64644. if (index_1 !== -1) {
  64645. this._scene.postProcesses.splice(index_1, 1);
  64646. }
  64647. }
  64648. else {
  64649. var index_2 = this._engine.postProcesses.indexOf(this);
  64650. if (index_2 !== -1) {
  64651. this._engine.postProcesses.splice(index_2, 1);
  64652. }
  64653. }
  64654. if (!camera) {
  64655. return;
  64656. }
  64657. camera.detachPostProcess(this);
  64658. var index = camera._postProcesses.indexOf(this);
  64659. if (index === 0 && camera._postProcesses.length > 0) {
  64660. var firstPostProcess = this._camera._getFirstPostProcess();
  64661. if (firstPostProcess) {
  64662. firstPostProcess.markTextureDirty();
  64663. }
  64664. }
  64665. this.onActivateObservable.clear();
  64666. this.onAfterRenderObservable.clear();
  64667. this.onApplyObservable.clear();
  64668. this.onBeforeRenderObservable.clear();
  64669. this.onSizeChangedObservable.clear();
  64670. };
  64671. return PostProcess;
  64672. }());
  64673. BABYLON.PostProcess = PostProcess;
  64674. })(BABYLON || (BABYLON = {}));
  64675. //# sourceMappingURL=babylon.postProcess.js.map
  64676. var BABYLON;
  64677. (function (BABYLON) {
  64678. var PassPostProcess = /** @class */ (function (_super) {
  64679. __extends(PassPostProcess, _super);
  64680. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64681. if (camera === void 0) { camera = null; }
  64682. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64683. if (blockCompilation === void 0) { blockCompilation = false; }
  64684. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64685. }
  64686. return PassPostProcess;
  64687. }(BABYLON.PostProcess));
  64688. BABYLON.PassPostProcess = PassPostProcess;
  64689. })(BABYLON || (BABYLON = {}));
  64690. //# sourceMappingURL=babylon.passPostProcess.js.map
  64691. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64692. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64693. s = arguments[i];
  64694. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64695. t[p] = s[p];
  64696. }
  64697. return t;
  64698. };
  64699. var BABYLON;
  64700. (function (BABYLON) {
  64701. /**
  64702. * Default implementation IShadowGenerator.
  64703. * This is the main object responsible of generating shadows in the framework.
  64704. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64705. */
  64706. var ShadowGenerator = /** @class */ (function () {
  64707. /**
  64708. * Creates a ShadowGenerator object.
  64709. * A ShadowGenerator is the required tool to use the shadows.
  64710. * Each light casting shadows needs to use its own ShadowGenerator.
  64711. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64712. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64713. * @param light The light object generating the shadows.
  64714. * @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.
  64715. */
  64716. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64717. this._bias = 0.00005;
  64718. this._normalBias = 0;
  64719. this._blurBoxOffset = 1;
  64720. this._blurScale = 2;
  64721. this._blurKernel = 1;
  64722. this._useKernelBlur = false;
  64723. this._filter = ShadowGenerator.FILTER_NONE;
  64724. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64725. this._contactHardeningLightSizeUVRatio = 0.1;
  64726. this._darkness = 0;
  64727. this._transparencyShadow = false;
  64728. /**
  64729. * Controls the extent to which the shadows fade out at the edge of the frustum
  64730. * Used only by directionals and spots
  64731. */
  64732. this.frustumEdgeFalloff = 0;
  64733. /**
  64734. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64735. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64736. * It might on the other hand introduce peter panning.
  64737. */
  64738. this.forceBackFacesOnly = false;
  64739. this._lightDirection = BABYLON.Vector3.Zero();
  64740. this._viewMatrix = BABYLON.Matrix.Zero();
  64741. this._projectionMatrix = BABYLON.Matrix.Zero();
  64742. this._transformMatrix = BABYLON.Matrix.Zero();
  64743. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64744. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64745. this._currentFaceIndex = 0;
  64746. this._currentFaceIndexCache = 0;
  64747. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64748. this._mapSize = mapSize;
  64749. this._light = light;
  64750. this._scene = light.getScene();
  64751. light._shadowGenerator = this;
  64752. // Texture type fallback from float to int if not supported.
  64753. var caps = this._scene.getEngine().getCaps();
  64754. if (!useFullFloatFirst) {
  64755. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64756. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64757. }
  64758. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64759. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64760. }
  64761. else {
  64762. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64763. }
  64764. }
  64765. else {
  64766. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64767. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64768. }
  64769. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64770. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64771. }
  64772. else {
  64773. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64774. }
  64775. }
  64776. this._initializeGenerator();
  64777. this._applyFilterValues();
  64778. }
  64779. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64780. /**
  64781. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64782. */
  64783. get: function () {
  64784. return this._bias;
  64785. },
  64786. /**
  64787. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64788. */
  64789. set: function (bias) {
  64790. this._bias = bias;
  64791. },
  64792. enumerable: true,
  64793. configurable: true
  64794. });
  64795. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64796. /**
  64797. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64798. */
  64799. get: function () {
  64800. return this._normalBias;
  64801. },
  64802. /**
  64803. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64804. */
  64805. set: function (normalBias) {
  64806. this._normalBias = normalBias;
  64807. },
  64808. enumerable: true,
  64809. configurable: true
  64810. });
  64811. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64812. /**
  64813. * Gets the blur box offset: offset applied during the blur pass.
  64814. * Only usefull if useKernelBlur = false
  64815. */
  64816. get: function () {
  64817. return this._blurBoxOffset;
  64818. },
  64819. /**
  64820. * Sets the blur box offset: offset applied during the blur pass.
  64821. * Only usefull if useKernelBlur = false
  64822. */
  64823. set: function (value) {
  64824. if (this._blurBoxOffset === value) {
  64825. return;
  64826. }
  64827. this._blurBoxOffset = value;
  64828. this._disposeBlurPostProcesses();
  64829. },
  64830. enumerable: true,
  64831. configurable: true
  64832. });
  64833. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64834. /**
  64835. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64836. * 2 means half of the size.
  64837. */
  64838. get: function () {
  64839. return this._blurScale;
  64840. },
  64841. /**
  64842. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64843. * 2 means half of the size.
  64844. */
  64845. set: function (value) {
  64846. if (this._blurScale === value) {
  64847. return;
  64848. }
  64849. this._blurScale = value;
  64850. this._disposeBlurPostProcesses();
  64851. },
  64852. enumerable: true,
  64853. configurable: true
  64854. });
  64855. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64856. /**
  64857. * Gets the blur kernel: kernel size of the blur pass.
  64858. * Only usefull if useKernelBlur = true
  64859. */
  64860. get: function () {
  64861. return this._blurKernel;
  64862. },
  64863. /**
  64864. * Sets the blur kernel: kernel size of the blur pass.
  64865. * Only usefull if useKernelBlur = true
  64866. */
  64867. set: function (value) {
  64868. if (this._blurKernel === value) {
  64869. return;
  64870. }
  64871. this._blurKernel = value;
  64872. this._disposeBlurPostProcesses();
  64873. },
  64874. enumerable: true,
  64875. configurable: true
  64876. });
  64877. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64878. /**
  64879. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64880. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64881. */
  64882. get: function () {
  64883. return this._useKernelBlur;
  64884. },
  64885. /**
  64886. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64887. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64888. */
  64889. set: function (value) {
  64890. if (this._useKernelBlur === value) {
  64891. return;
  64892. }
  64893. this._useKernelBlur = value;
  64894. this._disposeBlurPostProcesses();
  64895. },
  64896. enumerable: true,
  64897. configurable: true
  64898. });
  64899. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64900. /**
  64901. * Gets the depth scale used in ESM mode.
  64902. */
  64903. get: function () {
  64904. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64905. },
  64906. /**
  64907. * Sets the depth scale used in ESM mode.
  64908. * This can override the scale stored on the light.
  64909. */
  64910. set: function (value) {
  64911. this._depthScale = value;
  64912. },
  64913. enumerable: true,
  64914. configurable: true
  64915. });
  64916. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64917. /**
  64918. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64919. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64920. */
  64921. get: function () {
  64922. return this._filter;
  64923. },
  64924. /**
  64925. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64926. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64927. */
  64928. set: function (value) {
  64929. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64930. if (this._light.needCube()) {
  64931. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64932. this.useExponentialShadowMap = true;
  64933. return;
  64934. }
  64935. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64936. this.useCloseExponentialShadowMap = true;
  64937. return;
  64938. }
  64939. // PCF on cubemap would also be expensive
  64940. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64941. this.usePoissonSampling = true;
  64942. return;
  64943. }
  64944. }
  64945. // Weblg1 fallback for PCF.
  64946. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  64947. if (this._scene.getEngine().webGLVersion === 1) {
  64948. this.usePoissonSampling = true;
  64949. return;
  64950. }
  64951. }
  64952. if (this._filter === value) {
  64953. return;
  64954. }
  64955. this._filter = value;
  64956. this._disposeBlurPostProcesses();
  64957. this._applyFilterValues();
  64958. this._light._markMeshesAsLightDirty();
  64959. },
  64960. enumerable: true,
  64961. configurable: true
  64962. });
  64963. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  64964. /**
  64965. * Gets if the current filter is set to Poisson Sampling.
  64966. */
  64967. get: function () {
  64968. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  64969. },
  64970. /**
  64971. * Sets the current filter to Poisson Sampling.
  64972. */
  64973. set: function (value) {
  64974. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  64975. return;
  64976. }
  64977. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  64978. },
  64979. enumerable: true,
  64980. configurable: true
  64981. });
  64982. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  64983. /**
  64984. * Gets if the current filter is set to VSM.
  64985. * DEPRECATED. Should use useExponentialShadowMap instead.
  64986. */
  64987. get: function () {
  64988. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64989. return this.useExponentialShadowMap;
  64990. },
  64991. /**
  64992. * Sets the current filter is to VSM.
  64993. * DEPRECATED. Should use useExponentialShadowMap instead.
  64994. */
  64995. set: function (value) {
  64996. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  64997. this.useExponentialShadowMap = value;
  64998. },
  64999. enumerable: true,
  65000. configurable: true
  65001. });
  65002. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65003. /**
  65004. * Gets if the current filter is set to blurred VSM.
  65005. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65006. */
  65007. get: function () {
  65008. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65009. return this.useBlurExponentialShadowMap;
  65010. },
  65011. /**
  65012. * Sets the current filter is to blurred VSM.
  65013. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65014. */
  65015. set: function (value) {
  65016. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65017. this.useBlurExponentialShadowMap = value;
  65018. },
  65019. enumerable: true,
  65020. configurable: true
  65021. });
  65022. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65023. /**
  65024. * Gets if the current filter is set to ESM.
  65025. */
  65026. get: function () {
  65027. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65028. },
  65029. /**
  65030. * Sets the current filter is to ESM.
  65031. */
  65032. set: function (value) {
  65033. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65034. return;
  65035. }
  65036. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65037. },
  65038. enumerable: true,
  65039. configurable: true
  65040. });
  65041. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65042. /**
  65043. * Gets if the current filter is set to filtered ESM.
  65044. */
  65045. get: function () {
  65046. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65047. },
  65048. /**
  65049. * Gets if the current filter is set to filtered ESM.
  65050. */
  65051. set: function (value) {
  65052. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65053. return;
  65054. }
  65055. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65056. },
  65057. enumerable: true,
  65058. configurable: true
  65059. });
  65060. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65061. /**
  65062. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65063. * exponential to prevent steep falloff artifacts).
  65064. */
  65065. get: function () {
  65066. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65067. },
  65068. /**
  65069. * Sets the current filter to "close ESM" (using the inverse of the
  65070. * exponential to prevent steep falloff artifacts).
  65071. */
  65072. set: function (value) {
  65073. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65074. return;
  65075. }
  65076. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65082. /**
  65083. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65084. * exponential to prevent steep falloff artifacts).
  65085. */
  65086. get: function () {
  65087. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65088. },
  65089. /**
  65090. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65091. * exponential to prevent steep falloff artifacts).
  65092. */
  65093. set: function (value) {
  65094. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65095. return;
  65096. }
  65097. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65098. },
  65099. enumerable: true,
  65100. configurable: true
  65101. });
  65102. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65103. /**
  65104. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65105. */
  65106. get: function () {
  65107. return this.filter === ShadowGenerator.FILTER_PCF;
  65108. },
  65109. /**
  65110. * Sets the current filter to "PCF" (percentage closer filtering).
  65111. */
  65112. set: function (value) {
  65113. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65114. return;
  65115. }
  65116. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65117. },
  65118. enumerable: true,
  65119. configurable: true
  65120. });
  65121. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65122. /**
  65123. * Gets the PCF or PCSS Quality.
  65124. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65125. */
  65126. get: function () {
  65127. return this._filteringQuality;
  65128. },
  65129. /**
  65130. * Sets the PCF or PCSS Quality.
  65131. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65132. */
  65133. set: function (filteringQuality) {
  65134. this._filteringQuality = filteringQuality;
  65135. },
  65136. enumerable: true,
  65137. configurable: true
  65138. });
  65139. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65140. /**
  65141. * Gets if the current filter is set to "PCSS" (contact hardening).
  65142. */
  65143. get: function () {
  65144. return this.filter === ShadowGenerator.FILTER_PCSS;
  65145. },
  65146. /**
  65147. * Sets the current filter to "PCSS" (contact hardening).
  65148. */
  65149. set: function (value) {
  65150. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65151. return;
  65152. }
  65153. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65154. },
  65155. enumerable: true,
  65156. configurable: true
  65157. });
  65158. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65159. /**
  65160. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65161. * Using a ratio helps keeping shape stability independently of the map size.
  65162. *
  65163. * It does not account for the light projection as it was having too much
  65164. * instability during the light setup or during light position changes.
  65165. *
  65166. * Only valid if useContactHardeningShadow is true.
  65167. */
  65168. get: function () {
  65169. return this._contactHardeningLightSizeUVRatio;
  65170. },
  65171. /**
  65172. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65173. * Using a ratio helps keeping shape stability independently of the map size.
  65174. *
  65175. * It does not account for the light projection as it was having too much
  65176. * instability during the light setup or during light position changes.
  65177. *
  65178. * Only valid if useContactHardeningShadow is true.
  65179. */
  65180. set: function (contactHardeningLightSizeUVRatio) {
  65181. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65182. },
  65183. enumerable: true,
  65184. configurable: true
  65185. });
  65186. /**
  65187. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65188. * 0 means strongest and 1 would means no shadow.
  65189. * @returns the darkness.
  65190. */
  65191. ShadowGenerator.prototype.getDarkness = function () {
  65192. return this._darkness;
  65193. };
  65194. /**
  65195. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65196. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65197. * @returns the shadow generator allowing fluent coding.
  65198. */
  65199. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65200. if (darkness >= 1.0)
  65201. this._darkness = 1.0;
  65202. else if (darkness <= 0.0)
  65203. this._darkness = 0.0;
  65204. else
  65205. this._darkness = darkness;
  65206. return this;
  65207. };
  65208. /**
  65209. * Sets the ability to have transparent shadow (boolean).
  65210. * @param transparent True if transparent else False
  65211. * @returns the shadow generator allowing fluent coding
  65212. */
  65213. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65214. this._transparencyShadow = transparent;
  65215. return this;
  65216. };
  65217. /**
  65218. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65219. * @returns The render target texture if present otherwise, null
  65220. */
  65221. ShadowGenerator.prototype.getShadowMap = function () {
  65222. return this._shadowMap;
  65223. };
  65224. /**
  65225. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65226. * @returns The render target texture if the shadow map is present otherwise, null
  65227. */
  65228. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65229. if (this._shadowMap2) {
  65230. return this._shadowMap2;
  65231. }
  65232. return this._shadowMap;
  65233. };
  65234. /**
  65235. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65236. * @param mesh Mesh to add
  65237. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65238. * @returns the Shadow Generator itself
  65239. */
  65240. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65241. if (includeDescendants === void 0) { includeDescendants = true; }
  65242. if (!this._shadowMap) {
  65243. return this;
  65244. }
  65245. if (!this._shadowMap.renderList) {
  65246. this._shadowMap.renderList = [];
  65247. }
  65248. this._shadowMap.renderList.push(mesh);
  65249. if (includeDescendants) {
  65250. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65251. }
  65252. return this;
  65253. var _a;
  65254. };
  65255. /**
  65256. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65257. * @param mesh Mesh to remove
  65258. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65259. * @returns the Shadow Generator itself
  65260. */
  65261. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65262. if (includeDescendants === void 0) { includeDescendants = true; }
  65263. if (!this._shadowMap || !this._shadowMap.renderList) {
  65264. return this;
  65265. }
  65266. var index = this._shadowMap.renderList.indexOf(mesh);
  65267. if (index !== -1) {
  65268. this._shadowMap.renderList.splice(index, 1);
  65269. }
  65270. if (includeDescendants) {
  65271. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65272. var child = _a[_i];
  65273. this.removeShadowCaster(child);
  65274. }
  65275. }
  65276. return this;
  65277. };
  65278. /**
  65279. * Returns the associated light object.
  65280. * @returns the light generating the shadow
  65281. */
  65282. ShadowGenerator.prototype.getLight = function () {
  65283. return this._light;
  65284. };
  65285. ShadowGenerator.prototype._initializeGenerator = function () {
  65286. this._light._markMeshesAsLightDirty();
  65287. this._initializeShadowMap();
  65288. };
  65289. ShadowGenerator.prototype._initializeShadowMap = function () {
  65290. var _this = this;
  65291. // Render target
  65292. var engine = this._scene.getEngine();
  65293. if (engine.webGLVersion > 1) {
  65294. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65295. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65296. }
  65297. else {
  65298. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65299. }
  65300. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65301. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65302. this._shadowMap.anisotropicFilteringLevel = 1;
  65303. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65304. this._shadowMap.renderParticles = false;
  65305. this._shadowMap.ignoreCameraViewport = true;
  65306. // Record Face Index before render.
  65307. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65308. _this._currentFaceIndex = faceIndex;
  65309. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65310. engine.setColorWrite(false);
  65311. }
  65312. });
  65313. // Custom render function.
  65314. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65315. // Blur if required afer render.
  65316. this._shadowMap.onAfterUnbindObservable.add(function () {
  65317. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65318. engine.setColorWrite(true);
  65319. }
  65320. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65321. return;
  65322. }
  65323. var shadowMap = _this.getShadowMapForRendering();
  65324. if (shadowMap) {
  65325. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65326. }
  65327. });
  65328. // Clear according to the chosen filter.
  65329. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65330. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65331. this._shadowMap.onClearObservable.add(function (engine) {
  65332. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65333. engine.clear(clearOne, false, true, false);
  65334. }
  65335. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65336. engine.clear(clearZero, true, true, false);
  65337. }
  65338. else {
  65339. engine.clear(clearOne, true, true, false);
  65340. }
  65341. });
  65342. };
  65343. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65344. var _this = this;
  65345. var engine = this._scene.getEngine();
  65346. var targetSize = this._mapSize / this.blurScale;
  65347. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65348. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65349. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65350. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65351. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65352. }
  65353. if (this.useKernelBlur) {
  65354. 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);
  65355. this._kernelBlurXPostprocess.width = targetSize;
  65356. this._kernelBlurXPostprocess.height = targetSize;
  65357. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65358. effect.setTexture("textureSampler", _this._shadowMap);
  65359. });
  65360. 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);
  65361. this._kernelBlurXPostprocess.autoClear = false;
  65362. this._kernelBlurYPostprocess.autoClear = false;
  65363. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65364. this._kernelBlurXPostprocess.packedFloat = true;
  65365. this._kernelBlurYPostprocess.packedFloat = true;
  65366. }
  65367. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65368. }
  65369. else {
  65370. 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);
  65371. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65372. effect.setFloat2("screenSize", targetSize, targetSize);
  65373. effect.setTexture("textureSampler", _this._shadowMap);
  65374. });
  65375. this._boxBlurPostprocess.autoClear = false;
  65376. this._blurPostProcesses = [this._boxBlurPostprocess];
  65377. }
  65378. };
  65379. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65380. var index;
  65381. var engine = this._scene.getEngine();
  65382. if (depthOnlySubMeshes.length) {
  65383. engine.setColorWrite(false);
  65384. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65385. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65386. }
  65387. engine.setColorWrite(true);
  65388. }
  65389. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65390. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65391. }
  65392. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65393. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65394. }
  65395. if (this._transparencyShadow) {
  65396. for (index = 0; index < transparentSubMeshes.length; index++) {
  65397. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65398. }
  65399. }
  65400. };
  65401. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65402. var _this = this;
  65403. var mesh = subMesh.getRenderingMesh();
  65404. var scene = this._scene;
  65405. var engine = scene.getEngine();
  65406. var material = subMesh.getMaterial();
  65407. if (!material) {
  65408. return;
  65409. }
  65410. // Culling
  65411. engine.setState(material.backFaceCulling);
  65412. // Managing instances
  65413. var batch = mesh._getInstancesRenderList(subMesh._id);
  65414. if (batch.mustReturn) {
  65415. return;
  65416. }
  65417. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65418. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65419. engine.enableEffect(this._effect);
  65420. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65421. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65422. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65423. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65424. this._effect.setVector3("lightData", this._cachedDirection);
  65425. }
  65426. else {
  65427. this._effect.setVector3("lightData", this._cachedPosition);
  65428. }
  65429. if (scene.activeCamera) {
  65430. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65431. }
  65432. // Alpha test
  65433. if (material && material.needAlphaTesting()) {
  65434. var alphaTexture = material.getAlphaTestTexture();
  65435. if (alphaTexture) {
  65436. this._effect.setTexture("diffuseSampler", alphaTexture);
  65437. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65438. }
  65439. }
  65440. // Bones
  65441. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65442. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65443. }
  65444. // Morph targets
  65445. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65446. if (this.forceBackFacesOnly) {
  65447. engine.setState(true, 0, false, true);
  65448. }
  65449. // Draw
  65450. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65451. if (this.forceBackFacesOnly) {
  65452. engine.setState(true, 0, false, false);
  65453. }
  65454. }
  65455. else {
  65456. // Need to reset refresh rate of the shadowMap
  65457. if (this._shadowMap) {
  65458. this._shadowMap.resetRefreshCounter();
  65459. }
  65460. }
  65461. };
  65462. ShadowGenerator.prototype._applyFilterValues = function () {
  65463. if (!this._shadowMap) {
  65464. return;
  65465. }
  65466. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65467. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65468. }
  65469. else {
  65470. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65471. }
  65472. };
  65473. /**
  65474. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65475. * @param onCompiled Callback triggered at the and of the effects compilation
  65476. * @param options Sets of optional options forcing the compilation with different modes
  65477. */
  65478. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65479. var _this = this;
  65480. var localOptions = __assign({ useInstances: false }, options);
  65481. var shadowMap = this.getShadowMap();
  65482. if (!shadowMap) {
  65483. if (onCompiled) {
  65484. onCompiled(this);
  65485. }
  65486. return;
  65487. }
  65488. var renderList = shadowMap.renderList;
  65489. if (!renderList) {
  65490. if (onCompiled) {
  65491. onCompiled(this);
  65492. }
  65493. return;
  65494. }
  65495. var subMeshes = new Array();
  65496. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65497. var mesh = renderList_1[_i];
  65498. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65499. }
  65500. if (subMeshes.length === 0) {
  65501. if (onCompiled) {
  65502. onCompiled(this);
  65503. }
  65504. return;
  65505. }
  65506. var currentIndex = 0;
  65507. var checkReady = function () {
  65508. if (!_this._scene || !_this._scene.getEngine()) {
  65509. return;
  65510. }
  65511. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65512. currentIndex++;
  65513. if (currentIndex >= subMeshes.length) {
  65514. if (onCompiled) {
  65515. onCompiled(_this);
  65516. }
  65517. return;
  65518. }
  65519. }
  65520. setTimeout(checkReady, 16);
  65521. };
  65522. checkReady();
  65523. };
  65524. /**
  65525. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65526. * @param options Sets of optional options forcing the compilation with different modes
  65527. * @returns A promise that resolves when the compilation completes
  65528. */
  65529. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65530. var _this = this;
  65531. return new Promise(function (resolve) {
  65532. _this.forceCompilation(function () {
  65533. resolve();
  65534. }, options);
  65535. });
  65536. };
  65537. /**
  65538. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65539. * @param subMesh The submesh we want to render in the shadow map
  65540. * @param useInstances Defines wether will draw in the map using instances
  65541. * @returns true if ready otherwise, false
  65542. */
  65543. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65544. var defines = [];
  65545. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65546. defines.push("#define FLOAT");
  65547. }
  65548. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65549. defines.push("#define ESM");
  65550. }
  65551. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65552. defines.push("#define DEPTHTEXTURE");
  65553. }
  65554. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65555. var mesh = subMesh.getMesh();
  65556. var material = subMesh.getMaterial();
  65557. // Normal bias.
  65558. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65559. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65560. defines.push("#define NORMAL");
  65561. if (mesh.nonUniformScaling) {
  65562. defines.push("#define NONUNIFORMSCALING");
  65563. }
  65564. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65565. defines.push("#define DIRECTIONINLIGHTDATA");
  65566. }
  65567. }
  65568. // Alpha test
  65569. if (material && material.needAlphaTesting()) {
  65570. var alphaTexture = material.getAlphaTestTexture();
  65571. if (alphaTexture) {
  65572. defines.push("#define ALPHATEST");
  65573. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65574. attribs.push(BABYLON.VertexBuffer.UVKind);
  65575. defines.push("#define UV1");
  65576. }
  65577. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65578. if (alphaTexture.coordinatesIndex === 1) {
  65579. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65580. defines.push("#define UV2");
  65581. }
  65582. }
  65583. }
  65584. }
  65585. // Bones
  65586. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65587. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65588. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65589. if (mesh.numBoneInfluencers > 4) {
  65590. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65591. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65592. }
  65593. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65594. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65595. }
  65596. else {
  65597. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65598. }
  65599. // Morph targets
  65600. var manager = mesh.morphTargetManager;
  65601. var morphInfluencers = 0;
  65602. if (manager) {
  65603. if (manager.numInfluencers > 0) {
  65604. defines.push("#define MORPHTARGETS");
  65605. morphInfluencers = manager.numInfluencers;
  65606. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65607. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65608. }
  65609. }
  65610. // Instances
  65611. if (useInstances) {
  65612. defines.push("#define INSTANCES");
  65613. attribs.push("world0");
  65614. attribs.push("world1");
  65615. attribs.push("world2");
  65616. attribs.push("world3");
  65617. }
  65618. // Get correct effect
  65619. var join = defines.join("\n");
  65620. if (this._cachedDefines !== join) {
  65621. this._cachedDefines = join;
  65622. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65623. }
  65624. if (!this._effect.isReady()) {
  65625. return false;
  65626. }
  65627. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65628. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65629. this._initializeBlurRTTAndPostProcesses();
  65630. }
  65631. }
  65632. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65633. return false;
  65634. }
  65635. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65636. return false;
  65637. }
  65638. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65639. return false;
  65640. }
  65641. return true;
  65642. };
  65643. /**
  65644. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65645. * @param defines Defines of the material we want to update
  65646. * @param lightIndex Index of the light in the enabled light list of the material
  65647. */
  65648. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65649. var scene = this._scene;
  65650. var light = this._light;
  65651. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65652. return;
  65653. }
  65654. defines["SHADOW" + lightIndex] = true;
  65655. if (this.useContactHardeningShadow) {
  65656. defines["SHADOWPCSS" + lightIndex] = true;
  65657. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65658. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65659. }
  65660. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65661. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65662. }
  65663. // else default to high.
  65664. }
  65665. if (this.usePercentageCloserFiltering) {
  65666. defines["SHADOWPCF" + lightIndex] = true;
  65667. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65668. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65669. }
  65670. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65671. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65672. }
  65673. // else default to high.
  65674. }
  65675. else if (this.usePoissonSampling) {
  65676. defines["SHADOWPOISSON" + lightIndex] = true;
  65677. }
  65678. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65679. defines["SHADOWESM" + lightIndex] = true;
  65680. }
  65681. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65682. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65683. }
  65684. if (light.needCube()) {
  65685. defines["SHADOWCUBE" + lightIndex] = true;
  65686. }
  65687. };
  65688. /**
  65689. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65690. * defined in the generator but impacting the effect).
  65691. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65692. * @param effect The effect we are binfing the information for
  65693. */
  65694. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65695. var light = this._light;
  65696. var scene = this._scene;
  65697. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65698. return;
  65699. }
  65700. var camera = scene.activeCamera;
  65701. if (!camera) {
  65702. return;
  65703. }
  65704. var shadowMap = this.getShadowMap();
  65705. if (!shadowMap) {
  65706. return;
  65707. }
  65708. if (!light.needCube()) {
  65709. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65710. }
  65711. // Only PCF uses depth stencil texture.
  65712. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65713. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65714. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65715. }
  65716. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65717. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65718. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65719. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65720. }
  65721. else {
  65722. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65723. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65724. }
  65725. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65726. };
  65727. /**
  65728. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65729. * (eq to shadow prjection matrix * light transform matrix)
  65730. * @returns The transform matrix used to create the shadow map
  65731. */
  65732. ShadowGenerator.prototype.getTransformMatrix = function () {
  65733. var scene = this._scene;
  65734. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65735. return this._transformMatrix;
  65736. }
  65737. this._currentRenderID = scene.getRenderId();
  65738. this._currentFaceIndexCache = this._currentFaceIndex;
  65739. var lightPosition = this._light.position;
  65740. if (this._light.computeTransformedInformation()) {
  65741. lightPosition = this._light.transformedPosition;
  65742. }
  65743. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65744. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65745. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65746. }
  65747. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65748. this._cachedPosition.copyFrom(lightPosition);
  65749. this._cachedDirection.copyFrom(this._lightDirection);
  65750. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65751. var shadowMap = this.getShadowMap();
  65752. if (shadowMap) {
  65753. var renderList = shadowMap.renderList;
  65754. if (renderList) {
  65755. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65756. }
  65757. }
  65758. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65759. }
  65760. return this._transformMatrix;
  65761. };
  65762. /**
  65763. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65764. * Cube and 2D textures for instance.
  65765. */
  65766. ShadowGenerator.prototype.recreateShadowMap = function () {
  65767. var shadowMap = this._shadowMap;
  65768. if (!shadowMap) {
  65769. return;
  65770. }
  65771. // Track render list.
  65772. var renderList = shadowMap.renderList;
  65773. // Clean up existing data.
  65774. this._disposeRTTandPostProcesses();
  65775. // Reinitializes.
  65776. this._initializeGenerator();
  65777. // Reaffect the filter to ensure a correct fallback if necessary.
  65778. this.filter = this.filter;
  65779. // Reaffect the filter.
  65780. this._applyFilterValues();
  65781. // Reaffect Render List.
  65782. this._shadowMap.renderList = renderList;
  65783. };
  65784. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65785. if (this._shadowMap2) {
  65786. this._shadowMap2.dispose();
  65787. this._shadowMap2 = null;
  65788. }
  65789. if (this._boxBlurPostprocess) {
  65790. this._boxBlurPostprocess.dispose();
  65791. this._boxBlurPostprocess = null;
  65792. }
  65793. if (this._kernelBlurXPostprocess) {
  65794. this._kernelBlurXPostprocess.dispose();
  65795. this._kernelBlurXPostprocess = null;
  65796. }
  65797. if (this._kernelBlurYPostprocess) {
  65798. this._kernelBlurYPostprocess.dispose();
  65799. this._kernelBlurYPostprocess = null;
  65800. }
  65801. this._blurPostProcesses = [];
  65802. };
  65803. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65804. if (this._shadowMap) {
  65805. this._shadowMap.dispose();
  65806. this._shadowMap = null;
  65807. }
  65808. this._disposeBlurPostProcesses();
  65809. };
  65810. /**
  65811. * Disposes the ShadowGenerator.
  65812. * Returns nothing.
  65813. */
  65814. ShadowGenerator.prototype.dispose = function () {
  65815. this._disposeRTTandPostProcesses();
  65816. if (this._light) {
  65817. this._light._shadowGenerator = null;
  65818. this._light._markMeshesAsLightDirty();
  65819. }
  65820. };
  65821. /**
  65822. * Serializes the shadow generator setup to a json object.
  65823. * @returns The serialized JSON object
  65824. */
  65825. ShadowGenerator.prototype.serialize = function () {
  65826. var serializationObject = {};
  65827. var shadowMap = this.getShadowMap();
  65828. if (!shadowMap) {
  65829. return serializationObject;
  65830. }
  65831. serializationObject.lightId = this._light.id;
  65832. serializationObject.mapSize = shadowMap.getRenderSize();
  65833. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65834. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65835. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65836. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65837. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65838. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65839. serializationObject.depthScale = this.depthScale;
  65840. serializationObject.darkness = this.getDarkness();
  65841. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65842. serializationObject.blurKernel = this.blurKernel;
  65843. serializationObject.blurScale = this.blurScale;
  65844. serializationObject.useKernelBlur = this.useKernelBlur;
  65845. serializationObject.transparencyShadow = this._transparencyShadow;
  65846. serializationObject.bias = this.bias;
  65847. serializationObject.normalBias = this.normalBias;
  65848. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65849. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65850. serializationObject.filteringQuality = this.filteringQuality;
  65851. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65852. serializationObject.renderList = [];
  65853. if (shadowMap.renderList) {
  65854. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65855. var mesh = shadowMap.renderList[meshIndex];
  65856. serializationObject.renderList.push(mesh.id);
  65857. }
  65858. }
  65859. return serializationObject;
  65860. };
  65861. /**
  65862. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65863. * @param parsedShadowGenerator The JSON object to parse
  65864. * @param scene The scene to create the shadow map for
  65865. * @returns The parsed shadow generator
  65866. */
  65867. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65868. //casting to point light, as light is missing the position attr and typescript complains.
  65869. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65870. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65871. var shadowMap = shadowGenerator.getShadowMap();
  65872. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65873. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65874. meshes.forEach(function (mesh) {
  65875. if (!shadowMap) {
  65876. return;
  65877. }
  65878. if (!shadowMap.renderList) {
  65879. shadowMap.renderList = [];
  65880. }
  65881. shadowMap.renderList.push(mesh);
  65882. });
  65883. }
  65884. if (parsedShadowGenerator.usePoissonSampling) {
  65885. shadowGenerator.usePoissonSampling = true;
  65886. }
  65887. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65888. shadowGenerator.useExponentialShadowMap = true;
  65889. }
  65890. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65891. shadowGenerator.useBlurExponentialShadowMap = true;
  65892. }
  65893. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65894. shadowGenerator.useCloseExponentialShadowMap = true;
  65895. }
  65896. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65897. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65898. }
  65899. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65900. shadowGenerator.usePercentageCloserFiltering = true;
  65901. }
  65902. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65903. shadowGenerator.useContactHardeningShadow = true;
  65904. }
  65905. if (parsedShadowGenerator.filteringQuality) {
  65906. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65907. }
  65908. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65909. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65910. }
  65911. // Backward compat
  65912. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65913. shadowGenerator.useExponentialShadowMap = true;
  65914. }
  65915. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65916. shadowGenerator.useBlurExponentialShadowMap = true;
  65917. }
  65918. if (parsedShadowGenerator.depthScale) {
  65919. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65920. }
  65921. if (parsedShadowGenerator.blurScale) {
  65922. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65923. }
  65924. if (parsedShadowGenerator.blurBoxOffset) {
  65925. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65926. }
  65927. if (parsedShadowGenerator.useKernelBlur) {
  65928. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65929. }
  65930. if (parsedShadowGenerator.blurKernel) {
  65931. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65932. }
  65933. if (parsedShadowGenerator.bias !== undefined) {
  65934. shadowGenerator.bias = parsedShadowGenerator.bias;
  65935. }
  65936. if (parsedShadowGenerator.normalBias !== undefined) {
  65937. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65938. }
  65939. if (parsedShadowGenerator.darkness) {
  65940. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  65941. }
  65942. if (parsedShadowGenerator.transparencyShadow) {
  65943. shadowGenerator.setTransparencyShadow(true);
  65944. }
  65945. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  65946. return shadowGenerator;
  65947. };
  65948. /**
  65949. * Shadow generator mode None: no filtering applied.
  65950. */
  65951. ShadowGenerator.FILTER_NONE = 0;
  65952. /**
  65953. * Shadow generator mode ESM: Exponential Shadow Mapping.
  65954. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65955. */
  65956. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  65957. /**
  65958. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  65959. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  65960. */
  65961. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  65962. /**
  65963. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  65964. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65965. */
  65966. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  65967. /**
  65968. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  65969. * edge artifacts on steep falloff.
  65970. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65971. */
  65972. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  65973. /**
  65974. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  65975. * edge artifacts on steep falloff.
  65976. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  65977. */
  65978. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  65979. /**
  65980. * Shadow generator mode PCF: Percentage Closer Filtering
  65981. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65982. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  65983. */
  65984. ShadowGenerator.FILTER_PCF = 6;
  65985. /**
  65986. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  65987. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  65988. * Contact Hardening
  65989. */
  65990. ShadowGenerator.FILTER_PCSS = 7;
  65991. /**
  65992. * Reserved for PCF and PCSS
  65993. * Highest Quality.
  65994. *
  65995. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  65996. *
  65997. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  65998. */
  65999. ShadowGenerator.QUALITY_HIGH = 0;
  66000. /**
  66001. * Reserved for PCF and PCSS
  66002. * Good tradeoff for quality/perf cross devices
  66003. *
  66004. * Execute PCF on a 3*3 kernel.
  66005. *
  66006. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66007. */
  66008. ShadowGenerator.QUALITY_MEDIUM = 1;
  66009. /**
  66010. * Reserved for PCF and PCSS
  66011. * The lowest quality but the fastest.
  66012. *
  66013. * Execute PCF on a 1*1 kernel.
  66014. *
  66015. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66016. */
  66017. ShadowGenerator.QUALITY_LOW = 2;
  66018. return ShadowGenerator;
  66019. }());
  66020. BABYLON.ShadowGenerator = ShadowGenerator;
  66021. })(BABYLON || (BABYLON = {}));
  66022. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66023. var BABYLON;
  66024. (function (BABYLON) {
  66025. var DefaultLoadingScreen = /** @class */ (function () {
  66026. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66027. if (_loadingText === void 0) { _loadingText = ""; }
  66028. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66029. var _this = this;
  66030. this._renderingCanvas = _renderingCanvas;
  66031. this._loadingText = _loadingText;
  66032. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66033. // Resize
  66034. this._resizeLoadingUI = function () {
  66035. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66036. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66037. if (!_this._loadingDiv) {
  66038. return;
  66039. }
  66040. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66041. _this._loadingDiv.style.left = canvasRect.left + "px";
  66042. _this._loadingDiv.style.top = canvasRect.top + "px";
  66043. _this._loadingDiv.style.width = canvasRect.width + "px";
  66044. _this._loadingDiv.style.height = canvasRect.height + "px";
  66045. };
  66046. }
  66047. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66048. if (this._loadingDiv) {
  66049. // Do not add a loading screen if there is already one
  66050. return;
  66051. }
  66052. this._loadingDiv = document.createElement("div");
  66053. this._loadingDiv.id = "babylonjsLoadingDiv";
  66054. this._loadingDiv.style.opacity = "0";
  66055. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66056. this._loadingDiv.style.pointerEvents = "none";
  66057. // Loading text
  66058. this._loadingTextDiv = document.createElement("div");
  66059. this._loadingTextDiv.style.position = "absolute";
  66060. this._loadingTextDiv.style.left = "0";
  66061. this._loadingTextDiv.style.top = "50%";
  66062. this._loadingTextDiv.style.marginTop = "80px";
  66063. this._loadingTextDiv.style.width = "100%";
  66064. this._loadingTextDiv.style.height = "20px";
  66065. this._loadingTextDiv.style.fontFamily = "Arial";
  66066. this._loadingTextDiv.style.fontSize = "14px";
  66067. this._loadingTextDiv.style.color = "white";
  66068. this._loadingTextDiv.style.textAlign = "center";
  66069. this._loadingTextDiv.innerHTML = "Loading";
  66070. this._loadingDiv.appendChild(this._loadingTextDiv);
  66071. //set the predefined text
  66072. this._loadingTextDiv.innerHTML = this._loadingText;
  66073. // Generating keyframes
  66074. var style = document.createElement('style');
  66075. style.type = 'text/css';
  66076. 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 }";
  66077. style.innerHTML = keyFrames;
  66078. document.getElementsByTagName('head')[0].appendChild(style);
  66079. // Loading img
  66080. var imgBack = new Image();
  66081. 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";
  66082. imgBack.style.position = "absolute";
  66083. imgBack.style.left = "50%";
  66084. imgBack.style.top = "50%";
  66085. imgBack.style.marginLeft = "-60px";
  66086. imgBack.style.marginTop = "-60px";
  66087. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66088. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66089. imgBack.style.transformOrigin = "50% 50%";
  66090. imgBack.style.webkitTransformOrigin = "50% 50%";
  66091. this._loadingDiv.appendChild(imgBack);
  66092. this._resizeLoadingUI();
  66093. window.addEventListener("resize", this._resizeLoadingUI);
  66094. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66095. document.body.appendChild(this._loadingDiv);
  66096. this._loadingDiv.style.opacity = "1";
  66097. };
  66098. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66099. var _this = this;
  66100. if (!this._loadingDiv) {
  66101. return;
  66102. }
  66103. var onTransitionEnd = function () {
  66104. if (!_this._loadingDiv) {
  66105. return;
  66106. }
  66107. document.body.removeChild(_this._loadingDiv);
  66108. window.removeEventListener("resize", _this._resizeLoadingUI);
  66109. _this._loadingDiv = null;
  66110. };
  66111. this._loadingDiv.style.opacity = "0";
  66112. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66113. };
  66114. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66115. set: function (text) {
  66116. this._loadingText = text;
  66117. if (this._loadingTextDiv) {
  66118. this._loadingTextDiv.innerHTML = this._loadingText;
  66119. }
  66120. },
  66121. enumerable: true,
  66122. configurable: true
  66123. });
  66124. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66125. get: function () {
  66126. return this._loadingDivBackgroundColor;
  66127. },
  66128. set: function (color) {
  66129. this._loadingDivBackgroundColor = color;
  66130. if (!this._loadingDiv) {
  66131. return;
  66132. }
  66133. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66134. },
  66135. enumerable: true,
  66136. configurable: true
  66137. });
  66138. return DefaultLoadingScreen;
  66139. }());
  66140. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66141. })(BABYLON || (BABYLON = {}));
  66142. //# sourceMappingURL=babylon.loadingScreen.js.map
  66143. var BABYLON;
  66144. (function (BABYLON) {
  66145. var SceneLoaderProgressEvent = /** @class */ (function () {
  66146. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66147. this.lengthComputable = lengthComputable;
  66148. this.loaded = loaded;
  66149. this.total = total;
  66150. }
  66151. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66152. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66153. };
  66154. return SceneLoaderProgressEvent;
  66155. }());
  66156. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66157. var SceneLoader = /** @class */ (function () {
  66158. function SceneLoader() {
  66159. }
  66160. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66161. get: function () {
  66162. return 0;
  66163. },
  66164. enumerable: true,
  66165. configurable: true
  66166. });
  66167. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66168. get: function () {
  66169. return 1;
  66170. },
  66171. enumerable: true,
  66172. configurable: true
  66173. });
  66174. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66175. get: function () {
  66176. return 2;
  66177. },
  66178. enumerable: true,
  66179. configurable: true
  66180. });
  66181. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66182. get: function () {
  66183. return 3;
  66184. },
  66185. enumerable: true,
  66186. configurable: true
  66187. });
  66188. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66189. get: function () {
  66190. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66191. },
  66192. set: function (value) {
  66193. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66194. },
  66195. enumerable: true,
  66196. configurable: true
  66197. });
  66198. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66199. get: function () {
  66200. return SceneLoader._ShowLoadingScreen;
  66201. },
  66202. set: function (value) {
  66203. SceneLoader._ShowLoadingScreen = value;
  66204. },
  66205. enumerable: true,
  66206. configurable: true
  66207. });
  66208. Object.defineProperty(SceneLoader, "loggingLevel", {
  66209. get: function () {
  66210. return SceneLoader._loggingLevel;
  66211. },
  66212. set: function (value) {
  66213. SceneLoader._loggingLevel = value;
  66214. },
  66215. enumerable: true,
  66216. configurable: true
  66217. });
  66218. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66219. get: function () {
  66220. return SceneLoader._CleanBoneMatrixWeights;
  66221. },
  66222. set: function (value) {
  66223. SceneLoader._CleanBoneMatrixWeights = value;
  66224. },
  66225. enumerable: true,
  66226. configurable: true
  66227. });
  66228. SceneLoader._getDefaultPlugin = function () {
  66229. return SceneLoader._registeredPlugins[".babylon"];
  66230. };
  66231. SceneLoader._getPluginForExtension = function (extension) {
  66232. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66233. if (registeredPlugin) {
  66234. return registeredPlugin;
  66235. }
  66236. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66237. return SceneLoader._getDefaultPlugin();
  66238. };
  66239. SceneLoader._getPluginForDirectLoad = function (data) {
  66240. for (var extension in SceneLoader._registeredPlugins) {
  66241. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66242. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66243. return SceneLoader._registeredPlugins[extension];
  66244. }
  66245. }
  66246. return SceneLoader._getDefaultPlugin();
  66247. };
  66248. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66249. if (sceneFilename.name) {
  66250. sceneFilename = sceneFilename.name;
  66251. }
  66252. var queryStringPosition = sceneFilename.indexOf("?");
  66253. if (queryStringPosition !== -1) {
  66254. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66255. }
  66256. var dotPosition = sceneFilename.lastIndexOf(".");
  66257. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66258. return SceneLoader._getPluginForExtension(extension);
  66259. };
  66260. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66261. SceneLoader._getDirectLoad = function (sceneFilename) {
  66262. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66263. return sceneFilename.substr(5);
  66264. }
  66265. return null;
  66266. };
  66267. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66268. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66269. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66270. var plugin;
  66271. if (registeredPlugin.plugin.createPlugin) {
  66272. plugin = registeredPlugin.plugin.createPlugin();
  66273. }
  66274. else {
  66275. plugin = registeredPlugin.plugin;
  66276. }
  66277. var useArrayBuffer = registeredPlugin.isBinary;
  66278. var database;
  66279. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66280. var dataCallback = function (data, responseURL) {
  66281. if (scene.isDisposed) {
  66282. onError("Scene has been disposed");
  66283. return;
  66284. }
  66285. scene.database = database;
  66286. onSuccess(plugin, data, responseURL);
  66287. };
  66288. var request = null;
  66289. var pluginDisposed = false;
  66290. var onDisposeObservable = plugin.onDisposeObservable;
  66291. if (onDisposeObservable) {
  66292. onDisposeObservable.add(function () {
  66293. pluginDisposed = true;
  66294. if (request) {
  66295. request.abort();
  66296. request = null;
  66297. }
  66298. onDispose();
  66299. });
  66300. }
  66301. var manifestChecked = function () {
  66302. if (pluginDisposed) {
  66303. return;
  66304. }
  66305. var url = rootUrl + sceneFilename;
  66306. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66307. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66308. } : undefined, database, useArrayBuffer, function (request, exception) {
  66309. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66310. });
  66311. };
  66312. if (directLoad) {
  66313. dataCallback(directLoad);
  66314. return plugin;
  66315. }
  66316. if (rootUrl.indexOf("file:") === -1) {
  66317. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  66318. if (canUseOfflineSupport) {
  66319. // Also check for exceptions
  66320. var exceptionFound = false;
  66321. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66322. var regex = _a[_i];
  66323. if (regex.test(rootUrl + sceneFilename)) {
  66324. exceptionFound = true;
  66325. break;
  66326. }
  66327. }
  66328. canUseOfflineSupport = !exceptionFound;
  66329. }
  66330. if (canUseOfflineSupport) {
  66331. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66332. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  66333. }
  66334. else {
  66335. manifestChecked();
  66336. }
  66337. }
  66338. // Loading file from disk via input file or drag'n'drop
  66339. else {
  66340. var fileOrString = sceneFilename;
  66341. if (fileOrString.name) { // File
  66342. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66343. }
  66344. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66345. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66346. }
  66347. else {
  66348. onError("Unable to find file named " + sceneFilename);
  66349. }
  66350. }
  66351. return plugin;
  66352. };
  66353. // Public functions
  66354. SceneLoader.GetPluginForExtension = function (extension) {
  66355. return SceneLoader._getPluginForExtension(extension).plugin;
  66356. };
  66357. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66358. return !!SceneLoader._registeredPlugins[extension];
  66359. };
  66360. SceneLoader.RegisterPlugin = function (plugin) {
  66361. if (typeof plugin.extensions === "string") {
  66362. var extension = plugin.extensions;
  66363. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66364. plugin: plugin,
  66365. isBinary: false
  66366. };
  66367. }
  66368. else {
  66369. var extensions = plugin.extensions;
  66370. Object.keys(extensions).forEach(function (extension) {
  66371. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66372. plugin: plugin,
  66373. isBinary: extensions[extension].isBinary
  66374. };
  66375. });
  66376. }
  66377. };
  66378. /**
  66379. * Import meshes into a scene
  66380. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66381. * @param rootUrl a string that defines the root url for scene and resources
  66382. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66383. * @param scene the instance of BABYLON.Scene to append to
  66384. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66385. * @param onProgress a callback with a progress event for each file being loaded
  66386. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66387. * @param pluginExtension the extension used to determine the plugin
  66388. * @returns The loaded plugin
  66389. */
  66390. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66391. if (onSuccess === void 0) { onSuccess = null; }
  66392. if (onProgress === void 0) { onProgress = null; }
  66393. if (onError === void 0) { onError = null; }
  66394. if (pluginExtension === void 0) { pluginExtension = null; }
  66395. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66396. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66397. return null;
  66398. }
  66399. var loadingToken = {};
  66400. scene._addPendingData(loadingToken);
  66401. var disposeHandler = function () {
  66402. scene._removePendingData(loadingToken);
  66403. };
  66404. var errorHandler = function (message, exception) {
  66405. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66406. if (onError) {
  66407. onError(scene, errorMessage, exception);
  66408. }
  66409. else {
  66410. BABYLON.Tools.Error(errorMessage);
  66411. // should the exception be thrown?
  66412. }
  66413. disposeHandler();
  66414. };
  66415. var progressHandler = onProgress ? function (event) {
  66416. try {
  66417. onProgress(event);
  66418. }
  66419. catch (e) {
  66420. errorHandler("Error in onProgress callback", e);
  66421. }
  66422. } : undefined;
  66423. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66424. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66425. if (onSuccess) {
  66426. try {
  66427. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66428. }
  66429. catch (e) {
  66430. errorHandler("Error in onSuccess callback", e);
  66431. }
  66432. }
  66433. scene._removePendingData(loadingToken);
  66434. };
  66435. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66436. if (plugin.rewriteRootURL) {
  66437. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66438. }
  66439. if (sceneFilename === "") {
  66440. if (sceneFilename === "") {
  66441. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66442. }
  66443. }
  66444. if (plugin.importMesh) {
  66445. var syncedPlugin = plugin;
  66446. var meshes = new Array();
  66447. var particleSystems = new Array();
  66448. var skeletons = new Array();
  66449. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66450. return;
  66451. }
  66452. scene.loadingPluginName = plugin.name;
  66453. successHandler(meshes, particleSystems, skeletons, []);
  66454. }
  66455. else {
  66456. var asyncedPlugin = plugin;
  66457. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66458. scene.loadingPluginName = plugin.name;
  66459. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66460. }).catch(function (error) {
  66461. errorHandler(error.message, error);
  66462. });
  66463. }
  66464. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66465. };
  66466. /**
  66467. * Import meshes into a scene
  66468. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66469. * @param rootUrl a string that defines the root url for scene and resources
  66470. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66471. * @param scene the instance of BABYLON.Scene to append to
  66472. * @param onProgress a callback with a progress event for each file being loaded
  66473. * @param pluginExtension the extension used to determine the plugin
  66474. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66475. */
  66476. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66477. if (onProgress === void 0) { onProgress = null; }
  66478. if (pluginExtension === void 0) { pluginExtension = null; }
  66479. return new Promise(function (resolve, reject) {
  66480. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66481. resolve({
  66482. meshes: meshes,
  66483. particleSystems: particleSystems,
  66484. skeletons: skeletons,
  66485. animationGroups: animationGroups
  66486. });
  66487. }, onProgress, function (scene, message, exception) {
  66488. reject(exception || new Error(message));
  66489. });
  66490. });
  66491. };
  66492. /**
  66493. * Load a scene
  66494. * @param rootUrl a string that defines the root url for scene and resources
  66495. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66496. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66497. * @param onSuccess a callback with the scene when import succeeds
  66498. * @param onProgress a callback with a progress event for each file being loaded
  66499. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66500. * @param pluginExtension the extension used to determine the plugin
  66501. * @returns The loaded plugin
  66502. */
  66503. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66504. if (onSuccess === void 0) { onSuccess = null; }
  66505. if (onProgress === void 0) { onProgress = null; }
  66506. if (onError === void 0) { onError = null; }
  66507. if (pluginExtension === void 0) { pluginExtension = null; }
  66508. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66509. };
  66510. /**
  66511. * Load a scene
  66512. * @param rootUrl a string that defines the root url for scene and resources
  66513. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66514. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66515. * @param onProgress a callback with a progress event for each file being loaded
  66516. * @param pluginExtension the extension used to determine the plugin
  66517. * @returns The loaded scene
  66518. */
  66519. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66520. if (onProgress === void 0) { onProgress = null; }
  66521. if (pluginExtension === void 0) { pluginExtension = null; }
  66522. return new Promise(function (resolve, reject) {
  66523. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66524. resolve(scene);
  66525. }, onProgress, function (scene, message, exception) {
  66526. reject(exception || new Error(message));
  66527. }, pluginExtension);
  66528. });
  66529. };
  66530. /**
  66531. * Append a scene
  66532. * @param rootUrl a string that defines the root url for scene and resources
  66533. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66534. * @param scene is the instance of BABYLON.Scene to append to
  66535. * @param onSuccess a callback with the scene when import succeeds
  66536. * @param onProgress a callback with a progress event for each file being loaded
  66537. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66538. * @param pluginExtension the extension used to determine the plugin
  66539. * @returns The loaded plugin
  66540. */
  66541. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66542. if (onSuccess === void 0) { onSuccess = null; }
  66543. if (onProgress === void 0) { onProgress = null; }
  66544. if (onError === void 0) { onError = null; }
  66545. if (pluginExtension === void 0) { pluginExtension = null; }
  66546. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66547. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66548. return null;
  66549. }
  66550. if (SceneLoader.ShowLoadingScreen) {
  66551. scene.getEngine().displayLoadingUI();
  66552. }
  66553. var loadingToken = {};
  66554. scene._addPendingData(loadingToken);
  66555. var disposeHandler = function () {
  66556. scene._removePendingData(loadingToken);
  66557. scene.getEngine().hideLoadingUI();
  66558. };
  66559. var errorHandler = function (message, exception) {
  66560. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66561. if (onError) {
  66562. onError(scene, errorMessage, exception);
  66563. }
  66564. else {
  66565. BABYLON.Tools.Error(errorMessage);
  66566. // should the exception be thrown?
  66567. }
  66568. disposeHandler();
  66569. };
  66570. var progressHandler = onProgress ? function (event) {
  66571. try {
  66572. onProgress(event);
  66573. }
  66574. catch (e) {
  66575. errorHandler("Error in onProgress callback", e);
  66576. }
  66577. } : undefined;
  66578. var successHandler = function () {
  66579. if (onSuccess) {
  66580. try {
  66581. onSuccess(scene);
  66582. }
  66583. catch (e) {
  66584. errorHandler("Error in onSuccess callback", e);
  66585. }
  66586. }
  66587. scene._removePendingData(loadingToken);
  66588. };
  66589. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66590. if (sceneFilename === "") {
  66591. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66592. }
  66593. if (plugin.load) {
  66594. var syncedPlugin = plugin;
  66595. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66596. return;
  66597. }
  66598. scene.loadingPluginName = plugin.name;
  66599. successHandler();
  66600. }
  66601. else {
  66602. var asyncedPlugin = plugin;
  66603. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66604. scene.loadingPluginName = plugin.name;
  66605. successHandler();
  66606. }).catch(function (error) {
  66607. errorHandler(error.message, error);
  66608. });
  66609. }
  66610. if (SceneLoader.ShowLoadingScreen) {
  66611. scene.executeWhenReady(function () {
  66612. scene.getEngine().hideLoadingUI();
  66613. });
  66614. }
  66615. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66616. };
  66617. /**
  66618. * Append a scene
  66619. * @param rootUrl a string that defines the root url for scene and resources
  66620. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66621. * @param scene is the instance of BABYLON.Scene to append to
  66622. * @param onProgress a callback with a progress event for each file being loaded
  66623. * @param pluginExtension the extension used to determine the plugin
  66624. * @returns The given scene
  66625. */
  66626. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66627. if (onProgress === void 0) { onProgress = null; }
  66628. if (pluginExtension === void 0) { pluginExtension = null; }
  66629. return new Promise(function (resolve, reject) {
  66630. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66631. resolve(scene);
  66632. }, onProgress, function (scene, message, exception) {
  66633. reject(exception || new Error(message));
  66634. }, pluginExtension);
  66635. });
  66636. };
  66637. /**
  66638. * Load a scene into an asset container
  66639. * @param rootUrl a string that defines the root url for scene and resources
  66640. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66641. * @param scene is the instance of BABYLON.Scene to append to
  66642. * @param onSuccess a callback with the scene when import succeeds
  66643. * @param onProgress a callback with a progress event for each file being loaded
  66644. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66645. * @param pluginExtension the extension used to determine the plugin
  66646. * @returns The loaded plugin
  66647. */
  66648. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66649. if (onSuccess === void 0) { onSuccess = null; }
  66650. if (onProgress === void 0) { onProgress = null; }
  66651. if (onError === void 0) { onError = null; }
  66652. if (pluginExtension === void 0) { pluginExtension = null; }
  66653. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66654. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66655. return null;
  66656. }
  66657. var loadingToken = {};
  66658. scene._addPendingData(loadingToken);
  66659. var disposeHandler = function () {
  66660. scene._removePendingData(loadingToken);
  66661. };
  66662. var errorHandler = function (message, exception) {
  66663. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66664. if (onError) {
  66665. onError(scene, errorMessage, exception);
  66666. }
  66667. else {
  66668. BABYLON.Tools.Error(errorMessage);
  66669. // should the exception be thrown?
  66670. }
  66671. disposeHandler();
  66672. };
  66673. var progressHandler = onProgress ? function (event) {
  66674. try {
  66675. onProgress(event);
  66676. }
  66677. catch (e) {
  66678. errorHandler("Error in onProgress callback", e);
  66679. }
  66680. } : undefined;
  66681. var successHandler = function (assets) {
  66682. if (onSuccess) {
  66683. try {
  66684. onSuccess(assets);
  66685. }
  66686. catch (e) {
  66687. errorHandler("Error in onSuccess callback", e);
  66688. }
  66689. }
  66690. scene._removePendingData(loadingToken);
  66691. };
  66692. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66693. if (plugin.loadAssetContainer) {
  66694. var syncedPlugin = plugin;
  66695. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66696. if (!assetContainer) {
  66697. return;
  66698. }
  66699. scene.loadingPluginName = plugin.name;
  66700. successHandler(assetContainer);
  66701. }
  66702. else if (plugin.loadAssetContainerAsync) {
  66703. var asyncedPlugin = plugin;
  66704. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66705. scene.loadingPluginName = plugin.name;
  66706. successHandler(assetContainer);
  66707. }).catch(function (error) {
  66708. errorHandler(error.message, error);
  66709. });
  66710. }
  66711. else {
  66712. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66713. }
  66714. if (SceneLoader.ShowLoadingScreen) {
  66715. scene.executeWhenReady(function () {
  66716. scene.getEngine().hideLoadingUI();
  66717. });
  66718. }
  66719. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66720. };
  66721. /**
  66722. * Load a scene into an asset container
  66723. * @param rootUrl a string that defines the root url for scene and resources
  66724. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66725. * @param scene is the instance of BABYLON.Scene to append to
  66726. * @param onProgress a callback with a progress event for each file being loaded
  66727. * @param pluginExtension the extension used to determine the plugin
  66728. * @returns The loaded asset container
  66729. */
  66730. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66731. if (onProgress === void 0) { onProgress = null; }
  66732. if (pluginExtension === void 0) { pluginExtension = null; }
  66733. return new Promise(function (resolve, reject) {
  66734. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66735. resolve(assetContainer);
  66736. }, onProgress, function (scene, message, exception) {
  66737. reject(exception || new Error(message));
  66738. }, pluginExtension);
  66739. });
  66740. };
  66741. // Flags
  66742. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66743. SceneLoader._ShowLoadingScreen = true;
  66744. SceneLoader._CleanBoneMatrixWeights = false;
  66745. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66746. // Members
  66747. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66748. SceneLoader._registeredPlugins = {};
  66749. return SceneLoader;
  66750. }());
  66751. BABYLON.SceneLoader = SceneLoader;
  66752. ;
  66753. })(BABYLON || (BABYLON = {}));
  66754. //# sourceMappingURL=babylon.sceneLoader.js.map
  66755. var BABYLON;
  66756. (function (BABYLON) {
  66757. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66758. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66759. var parsedMaterial = parsedData.materials[index];
  66760. if (parsedMaterial.id === id) {
  66761. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66762. }
  66763. }
  66764. return null;
  66765. };
  66766. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66767. for (var i in names) {
  66768. if (mesh.name === names[i]) {
  66769. hierarchyIds.push(mesh.id);
  66770. return true;
  66771. }
  66772. }
  66773. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66774. hierarchyIds.push(mesh.id);
  66775. return true;
  66776. }
  66777. return false;
  66778. };
  66779. var logOperation = function (operation, producer) {
  66780. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66781. };
  66782. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66783. if (addToScene === void 0) { addToScene = false; }
  66784. var container = new BABYLON.AssetContainer(scene);
  66785. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66786. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66787. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66788. // and avoid problems with multiple concurrent .babylon loads.
  66789. var log = "importScene has failed JSON parse";
  66790. try {
  66791. var parsedData = JSON.parse(data);
  66792. log = "";
  66793. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66794. var index;
  66795. var cache;
  66796. // Lights
  66797. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66798. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66799. var parsedLight = parsedData.lights[index];
  66800. var light = BABYLON.Light.Parse(parsedLight, scene);
  66801. if (light) {
  66802. container.lights.push(light);
  66803. log += (index === 0 ? "\n\tLights:" : "");
  66804. log += "\n\t\t" + light.toString(fullDetails);
  66805. }
  66806. }
  66807. }
  66808. // Animations
  66809. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66810. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66811. var parsedAnimation = parsedData.animations[index];
  66812. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66813. scene.animations.push(animation);
  66814. container.animations.push(animation);
  66815. log += (index === 0 ? "\n\tAnimations:" : "");
  66816. log += "\n\t\t" + animation.toString(fullDetails);
  66817. }
  66818. }
  66819. // Materials
  66820. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66821. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66822. var parsedMaterial = parsedData.materials[index];
  66823. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66824. container.materials.push(mat);
  66825. log += (index === 0 ? "\n\tMaterials:" : "");
  66826. log += "\n\t\t" + mat.toString(fullDetails);
  66827. }
  66828. }
  66829. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66830. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66831. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66832. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66833. container.multiMaterials.push(mmat);
  66834. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66835. log += "\n\t\t" + mmat.toString(fullDetails);
  66836. }
  66837. }
  66838. // Morph targets
  66839. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66840. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66841. var managerData = _a[_i];
  66842. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66843. }
  66844. }
  66845. // Skeletons
  66846. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66847. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66848. var parsedSkeleton = parsedData.skeletons[index];
  66849. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66850. container.skeletons.push(skeleton);
  66851. log += (index === 0 ? "\n\tSkeletons:" : "");
  66852. log += "\n\t\t" + skeleton.toString(fullDetails);
  66853. }
  66854. }
  66855. // Geometries
  66856. var geometries = parsedData.geometries;
  66857. if (geometries !== undefined && geometries !== null) {
  66858. var addedGeometry = new Array();
  66859. // Boxes
  66860. var boxes = geometries.boxes;
  66861. if (boxes !== undefined && boxes !== null) {
  66862. for (index = 0, cache = boxes.length; index < cache; index++) {
  66863. var parsedBox = boxes[index];
  66864. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66865. }
  66866. }
  66867. // Spheres
  66868. var spheres = geometries.spheres;
  66869. if (spheres !== undefined && spheres !== null) {
  66870. for (index = 0, cache = spheres.length; index < cache; index++) {
  66871. var parsedSphere = spheres[index];
  66872. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66873. }
  66874. }
  66875. // Cylinders
  66876. var cylinders = geometries.cylinders;
  66877. if (cylinders !== undefined && cylinders !== null) {
  66878. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66879. var parsedCylinder = cylinders[index];
  66880. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66881. }
  66882. }
  66883. // Toruses
  66884. var toruses = geometries.toruses;
  66885. if (toruses !== undefined && toruses !== null) {
  66886. for (index = 0, cache = toruses.length; index < cache; index++) {
  66887. var parsedTorus = toruses[index];
  66888. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66889. }
  66890. }
  66891. // Grounds
  66892. var grounds = geometries.grounds;
  66893. if (grounds !== undefined && grounds !== null) {
  66894. for (index = 0, cache = grounds.length; index < cache; index++) {
  66895. var parsedGround = grounds[index];
  66896. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66897. }
  66898. }
  66899. // Planes
  66900. var planes = geometries.planes;
  66901. if (planes !== undefined && planes !== null) {
  66902. for (index = 0, cache = planes.length; index < cache; index++) {
  66903. var parsedPlane = planes[index];
  66904. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66905. }
  66906. }
  66907. // TorusKnots
  66908. var torusKnots = geometries.torusKnots;
  66909. if (torusKnots !== undefined && torusKnots !== null) {
  66910. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66911. var parsedTorusKnot = torusKnots[index];
  66912. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66913. }
  66914. }
  66915. // VertexData
  66916. var vertexData = geometries.vertexData;
  66917. if (vertexData !== undefined && vertexData !== null) {
  66918. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66919. var parsedVertexData = vertexData[index];
  66920. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66921. }
  66922. }
  66923. addedGeometry.forEach(function (g) {
  66924. if (g) {
  66925. container.geometries.push(g);
  66926. }
  66927. });
  66928. }
  66929. // Transform nodes
  66930. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66931. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66932. var parsedTransformNode = parsedData.transformNodes[index];
  66933. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66934. container.transformNodes.push(node);
  66935. }
  66936. }
  66937. // Meshes
  66938. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66939. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66940. var parsedMesh = parsedData.meshes[index];
  66941. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  66942. container.meshes.push(mesh);
  66943. log += (index === 0 ? "\n\tMeshes:" : "");
  66944. log += "\n\t\t" + mesh.toString(fullDetails);
  66945. }
  66946. }
  66947. // Cameras
  66948. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  66949. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  66950. var parsedCamera = parsedData.cameras[index];
  66951. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  66952. container.cameras.push(camera);
  66953. log += (index === 0 ? "\n\tCameras:" : "");
  66954. log += "\n\t\t" + camera.toString(fullDetails);
  66955. }
  66956. }
  66957. // Browsing all the graph to connect the dots
  66958. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  66959. var camera = scene.cameras[index];
  66960. if (camera._waitingParentId) {
  66961. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  66962. camera._waitingParentId = null;
  66963. }
  66964. }
  66965. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  66966. var light_1 = scene.lights[index];
  66967. if (light_1 && light_1._waitingParentId) {
  66968. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  66969. light_1._waitingParentId = null;
  66970. }
  66971. }
  66972. // Sounds
  66973. // TODO: add sound
  66974. var loadedSounds = [];
  66975. var loadedSound;
  66976. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  66977. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  66978. var parsedSound = parsedData.sounds[index];
  66979. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  66980. if (!parsedSound.url)
  66981. parsedSound.url = parsedSound.name;
  66982. if (!loadedSounds[parsedSound.url]) {
  66983. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  66984. loadedSounds[parsedSound.url] = loadedSound;
  66985. container.sounds.push(loadedSound);
  66986. }
  66987. else {
  66988. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  66989. }
  66990. }
  66991. else {
  66992. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  66993. }
  66994. }
  66995. }
  66996. loadedSounds = [];
  66997. // Connect parents & children and parse actions
  66998. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  66999. var transformNode = scene.transformNodes[index];
  67000. if (transformNode._waitingParentId) {
  67001. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67002. transformNode._waitingParentId = null;
  67003. }
  67004. }
  67005. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67006. var mesh = scene.meshes[index];
  67007. if (mesh._waitingParentId) {
  67008. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67009. mesh._waitingParentId = null;
  67010. }
  67011. if (mesh._waitingActions) {
  67012. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67013. mesh._waitingActions = null;
  67014. }
  67015. }
  67016. // freeze world matrix application
  67017. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67018. var currentMesh = scene.meshes[index];
  67019. if (currentMesh._waitingFreezeWorldMatrix) {
  67020. currentMesh.freezeWorldMatrix();
  67021. currentMesh._waitingFreezeWorldMatrix = null;
  67022. }
  67023. else {
  67024. currentMesh.computeWorldMatrix(true);
  67025. }
  67026. }
  67027. // Particles Systems
  67028. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67029. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67030. var parsedParticleSystem = parsedData.particleSystems[index];
  67031. if (parsedParticleSystem.activeParticleCount) {
  67032. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67033. container.particleSystems.push(ps);
  67034. }
  67035. else {
  67036. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67037. container.particleSystems.push(ps);
  67038. }
  67039. }
  67040. }
  67041. // Lens flares
  67042. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67043. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67044. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67045. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67046. container.lensFlareSystems.push(lf);
  67047. }
  67048. }
  67049. // Shadows
  67050. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67051. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67052. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67053. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67054. container.shadowGenerators.push(sg);
  67055. }
  67056. }
  67057. // Lights exclusions / inclusions
  67058. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67059. var light_2 = scene.lights[index];
  67060. // Excluded check
  67061. if (light_2._excludedMeshesIds.length > 0) {
  67062. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67063. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67064. if (excludedMesh) {
  67065. light_2.excludedMeshes.push(excludedMesh);
  67066. }
  67067. }
  67068. light_2._excludedMeshesIds = [];
  67069. }
  67070. // Included check
  67071. if (light_2._includedOnlyMeshesIds.length > 0) {
  67072. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67073. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67074. if (includedOnlyMesh) {
  67075. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67076. }
  67077. }
  67078. light_2._includedOnlyMeshesIds = [];
  67079. }
  67080. }
  67081. // Effect layers
  67082. if (parsedData.effectLayers) {
  67083. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67084. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67085. container.effectLayers.push(effectLayer);
  67086. }
  67087. }
  67088. // Actions (scene)
  67089. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67090. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67091. }
  67092. if (!addToScene) {
  67093. container.removeAllFromScene();
  67094. }
  67095. }
  67096. catch (err) {
  67097. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67098. if (onError) {
  67099. onError(msg, err);
  67100. }
  67101. else {
  67102. BABYLON.Tools.Log(msg);
  67103. throw err;
  67104. }
  67105. }
  67106. finally {
  67107. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67108. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67109. }
  67110. }
  67111. return container;
  67112. };
  67113. BABYLON.SceneLoader.RegisterPlugin({
  67114. name: "babylon.js",
  67115. extensions: ".babylon",
  67116. canDirectLoad: function (data) {
  67117. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67118. return true;
  67119. }
  67120. return false;
  67121. },
  67122. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67123. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67124. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67125. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67126. // and avoid problems with multiple concurrent .babylon loads.
  67127. var log = "importMesh has failed JSON parse";
  67128. try {
  67129. var parsedData = JSON.parse(data);
  67130. log = "";
  67131. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67132. if (!meshesNames) {
  67133. meshesNames = null;
  67134. }
  67135. else if (!Array.isArray(meshesNames)) {
  67136. meshesNames = [meshesNames];
  67137. }
  67138. var hierarchyIds = new Array();
  67139. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67140. var loadedSkeletonsIds = [];
  67141. var loadedMaterialsIds = [];
  67142. var index;
  67143. var cache;
  67144. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67145. var parsedMesh = parsedData.meshes[index];
  67146. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67147. if (meshesNames !== null) {
  67148. // Remove found mesh name from list.
  67149. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67150. }
  67151. //Geometry?
  67152. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67153. //does the file contain geometries?
  67154. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67155. //find the correct geometry and add it to the scene
  67156. var found = false;
  67157. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67158. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67159. return;
  67160. }
  67161. else {
  67162. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67163. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67164. switch (geometryType) {
  67165. case "boxes":
  67166. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67167. break;
  67168. case "spheres":
  67169. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67170. break;
  67171. case "cylinders":
  67172. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67173. break;
  67174. case "toruses":
  67175. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67176. break;
  67177. case "grounds":
  67178. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67179. break;
  67180. case "planes":
  67181. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67182. break;
  67183. case "torusKnots":
  67184. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67185. break;
  67186. case "vertexData":
  67187. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67188. break;
  67189. }
  67190. found = true;
  67191. }
  67192. });
  67193. }
  67194. });
  67195. if (found === false) {
  67196. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67197. }
  67198. }
  67199. }
  67200. // Material ?
  67201. if (parsedMesh.materialId) {
  67202. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67203. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67204. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67205. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67206. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67207. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67208. var subMatId = parsedMultiMaterial.materials[matIndex];
  67209. loadedMaterialsIds.push(subMatId);
  67210. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67211. if (mat) {
  67212. log += "\n\tMaterial " + mat.toString(fullDetails);
  67213. }
  67214. }
  67215. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67216. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67217. if (mmat) {
  67218. materialFound = true;
  67219. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67220. }
  67221. break;
  67222. }
  67223. }
  67224. }
  67225. if (materialFound === false) {
  67226. loadedMaterialsIds.push(parsedMesh.materialId);
  67227. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67228. if (!mat) {
  67229. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67230. }
  67231. else {
  67232. log += "\n\tMaterial " + mat.toString(fullDetails);
  67233. }
  67234. }
  67235. }
  67236. // Skeleton ?
  67237. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67238. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67239. if (skeletonAlreadyLoaded === false) {
  67240. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67241. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67242. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67243. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67244. skeletons.push(skeleton);
  67245. loadedSkeletonsIds.push(parsedSkeleton.id);
  67246. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67247. }
  67248. }
  67249. }
  67250. }
  67251. // Morph targets ?
  67252. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67253. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67254. var managerData = _a[_i];
  67255. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67256. }
  67257. }
  67258. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67259. meshes.push(mesh);
  67260. log += "\n\tMesh " + mesh.toString(fullDetails);
  67261. }
  67262. }
  67263. // Connecting parents
  67264. var currentMesh;
  67265. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67266. currentMesh = scene.meshes[index];
  67267. if (currentMesh._waitingParentId) {
  67268. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67269. currentMesh._waitingParentId = null;
  67270. }
  67271. }
  67272. // freeze and compute world matrix application
  67273. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67274. currentMesh = scene.meshes[index];
  67275. if (currentMesh._waitingFreezeWorldMatrix) {
  67276. currentMesh.freezeWorldMatrix();
  67277. currentMesh._waitingFreezeWorldMatrix = null;
  67278. }
  67279. else {
  67280. currentMesh.computeWorldMatrix(true);
  67281. }
  67282. }
  67283. }
  67284. // Particles
  67285. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67286. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67287. var parsedParticleSystem = parsedData.particleSystems[index];
  67288. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67289. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67290. }
  67291. }
  67292. }
  67293. return true;
  67294. }
  67295. catch (err) {
  67296. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67297. if (onError) {
  67298. onError(msg, err);
  67299. }
  67300. else {
  67301. BABYLON.Tools.Log(msg);
  67302. throw err;
  67303. }
  67304. }
  67305. finally {
  67306. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67307. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67308. }
  67309. }
  67310. return false;
  67311. },
  67312. load: function (scene, data, rootUrl, onError) {
  67313. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67314. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67315. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67316. // and avoid problems with multiple concurrent .babylon loads.
  67317. var log = "importScene has failed JSON parse";
  67318. try {
  67319. var parsedData = JSON.parse(data);
  67320. log = "";
  67321. // Scene
  67322. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67323. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67324. }
  67325. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67326. scene.autoClear = parsedData.autoClear;
  67327. }
  67328. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67329. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67330. }
  67331. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67332. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67333. }
  67334. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67335. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67336. }
  67337. // Fog
  67338. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67339. scene.fogMode = parsedData.fogMode;
  67340. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67341. scene.fogStart = parsedData.fogStart;
  67342. scene.fogEnd = parsedData.fogEnd;
  67343. scene.fogDensity = parsedData.fogDensity;
  67344. log += "\tFog mode for scene: ";
  67345. switch (scene.fogMode) {
  67346. // getters not compiling, so using hardcoded
  67347. case 1:
  67348. log += "exp\n";
  67349. break;
  67350. case 2:
  67351. log += "exp2\n";
  67352. break;
  67353. case 3:
  67354. log += "linear\n";
  67355. break;
  67356. }
  67357. }
  67358. //Physics
  67359. if (parsedData.physicsEnabled) {
  67360. var physicsPlugin;
  67361. if (parsedData.physicsEngine === "cannon") {
  67362. physicsPlugin = new BABYLON.CannonJSPlugin();
  67363. }
  67364. else if (parsedData.physicsEngine === "oimo") {
  67365. physicsPlugin = new BABYLON.OimoJSPlugin();
  67366. }
  67367. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67368. //else - default engine, which is currently oimo
  67369. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67370. scene.enablePhysics(physicsGravity, physicsPlugin);
  67371. }
  67372. // Metadata
  67373. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67374. scene.metadata = parsedData.metadata;
  67375. }
  67376. //collisions, if defined. otherwise, default is true
  67377. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67378. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67379. }
  67380. scene.workerCollisions = !!parsedData.workerCollisions;
  67381. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67382. if (!container) {
  67383. return false;
  67384. }
  67385. if (parsedData.autoAnimate) {
  67386. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67387. }
  67388. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67389. scene.setActiveCameraByID(parsedData.activeCameraID);
  67390. }
  67391. // Environment texture
  67392. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67393. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67394. if (parsedData.createDefaultSkybox === true) {
  67395. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67396. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67397. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67398. }
  67399. }
  67400. // Finish
  67401. return true;
  67402. }
  67403. catch (err) {
  67404. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67405. if (onError) {
  67406. onError(msg, err);
  67407. }
  67408. else {
  67409. BABYLON.Tools.Log(msg);
  67410. throw err;
  67411. }
  67412. }
  67413. finally {
  67414. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67415. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67416. }
  67417. }
  67418. return false;
  67419. },
  67420. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67421. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67422. return container;
  67423. }
  67424. });
  67425. })(BABYLON || (BABYLON = {}));
  67426. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67427. var BABYLON;
  67428. (function (BABYLON) {
  67429. var FilesInput = /** @class */ (function () {
  67430. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67431. this.onProcessFileCallback = function () { return true; };
  67432. this._engine = engine;
  67433. this._currentScene = scene;
  67434. this._sceneLoadedCallback = sceneLoadedCallback;
  67435. this._progressCallback = progressCallback;
  67436. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67437. this._textureLoadingCallback = textureLoadingCallback;
  67438. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67439. this._onReloadCallback = onReloadCallback;
  67440. this._errorCallback = errorCallback;
  67441. }
  67442. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67443. var _this = this;
  67444. if (elementToMonitor) {
  67445. this._elementToMonitor = elementToMonitor;
  67446. this._dragEnterHandler = function (e) { _this.drag(e); };
  67447. this._dragOverHandler = function (e) { _this.drag(e); };
  67448. this._dropHandler = function (e) { _this.drop(e); };
  67449. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67450. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67451. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67452. }
  67453. };
  67454. FilesInput.prototype.dispose = function () {
  67455. if (!this._elementToMonitor) {
  67456. return;
  67457. }
  67458. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67459. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67460. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67461. };
  67462. FilesInput.prototype.renderFunction = function () {
  67463. if (this._additionalRenderLoopLogicCallback) {
  67464. this._additionalRenderLoopLogicCallback();
  67465. }
  67466. if (this._currentScene) {
  67467. if (this._textureLoadingCallback) {
  67468. var remaining = this._currentScene.getWaitingItemsCount();
  67469. if (remaining > 0) {
  67470. this._textureLoadingCallback(remaining);
  67471. }
  67472. }
  67473. this._currentScene.render();
  67474. }
  67475. };
  67476. FilesInput.prototype.drag = function (e) {
  67477. e.stopPropagation();
  67478. e.preventDefault();
  67479. };
  67480. FilesInput.prototype.drop = function (eventDrop) {
  67481. eventDrop.stopPropagation();
  67482. eventDrop.preventDefault();
  67483. this.loadFiles(eventDrop);
  67484. };
  67485. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67486. var _this = this;
  67487. var reader = folder.createReader();
  67488. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67489. reader.readEntries(function (entries) {
  67490. remaining.count += entries.length;
  67491. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67492. var entry = entries_1[_i];
  67493. if (entry.isFile) {
  67494. entry.file(function (file) {
  67495. file.correctName = relativePath + file.name;
  67496. files.push(file);
  67497. if (--remaining.count === 0) {
  67498. callback();
  67499. }
  67500. });
  67501. }
  67502. else if (entry.isDirectory) {
  67503. _this._traverseFolder(entry, files, remaining, callback);
  67504. }
  67505. }
  67506. if (--remaining.count) {
  67507. callback();
  67508. }
  67509. });
  67510. };
  67511. FilesInput.prototype._processFiles = function (files) {
  67512. for (var i = 0; i < files.length; i++) {
  67513. var name = files[i].correctName.toLowerCase();
  67514. var extension = name.split('.').pop();
  67515. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67516. continue;
  67517. }
  67518. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67519. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67520. this._sceneFileToLoad = files[i];
  67521. }
  67522. else {
  67523. FilesInput.FilesToLoad[name] = files[i];
  67524. }
  67525. }
  67526. };
  67527. FilesInput.prototype.loadFiles = function (event) {
  67528. var _this = this;
  67529. if (this._startingProcessingFilesCallback)
  67530. this._startingProcessingFilesCallback();
  67531. // Handling data transfer via drag'n'drop
  67532. if (event && event.dataTransfer && event.dataTransfer.files) {
  67533. this._filesToLoad = event.dataTransfer.files;
  67534. }
  67535. // Handling files from input files
  67536. if (event && event.target && event.target.files) {
  67537. this._filesToLoad = event.target.files;
  67538. }
  67539. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67540. var files_1 = new Array();
  67541. var folders = [];
  67542. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67543. for (var i = 0; i < this._filesToLoad.length; i++) {
  67544. var fileToLoad = this._filesToLoad[i];
  67545. var name_1 = fileToLoad.name.toLowerCase();
  67546. var entry = void 0;
  67547. fileToLoad.correctName = name_1;
  67548. if (items) {
  67549. var item = items[i];
  67550. if (item.getAsEntry) {
  67551. entry = item.getAsEntry();
  67552. }
  67553. else if (item.webkitGetAsEntry) {
  67554. entry = item.webkitGetAsEntry();
  67555. }
  67556. }
  67557. if (!entry) {
  67558. files_1.push(fileToLoad);
  67559. }
  67560. else {
  67561. if (entry.isDirectory) {
  67562. folders.push(entry);
  67563. }
  67564. else {
  67565. files_1.push(fileToLoad);
  67566. }
  67567. }
  67568. }
  67569. if (folders.length === 0) {
  67570. this._processFiles(files_1);
  67571. this._processReload();
  67572. }
  67573. else {
  67574. var remaining = { count: folders.length };
  67575. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67576. var folder = folders_1[_i];
  67577. this._traverseFolder(folder, files_1, remaining, function () {
  67578. _this._processFiles(files_1);
  67579. if (remaining.count === 0) {
  67580. _this._processReload();
  67581. }
  67582. });
  67583. }
  67584. }
  67585. }
  67586. };
  67587. FilesInput.prototype._processReload = function () {
  67588. if (this._onReloadCallback) {
  67589. this._onReloadCallback(this._sceneFileToLoad);
  67590. }
  67591. else {
  67592. this.reload();
  67593. }
  67594. };
  67595. FilesInput.prototype.reload = function () {
  67596. var _this = this;
  67597. // If a scene file has been provided
  67598. if (this._sceneFileToLoad) {
  67599. if (this._currentScene) {
  67600. if (BABYLON.Tools.errorsCount > 0) {
  67601. BABYLON.Tools.ClearLogCache();
  67602. }
  67603. this._engine.stopRenderLoop();
  67604. this._currentScene.dispose();
  67605. }
  67606. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67607. if (_this._progressCallback) {
  67608. _this._progressCallback(progress);
  67609. }
  67610. }).then(function (scene) {
  67611. _this._currentScene = scene;
  67612. if (_this._sceneLoadedCallback) {
  67613. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67614. }
  67615. // Wait for textures and shaders to be ready
  67616. _this._currentScene.executeWhenReady(function () {
  67617. _this._engine.runRenderLoop(function () {
  67618. _this.renderFunction();
  67619. });
  67620. });
  67621. }).catch(function (error) {
  67622. if (_this._errorCallback) {
  67623. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67624. }
  67625. });
  67626. }
  67627. else {
  67628. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67629. }
  67630. };
  67631. FilesInput.FilesToLoad = {};
  67632. return FilesInput;
  67633. }());
  67634. BABYLON.FilesInput = FilesInput;
  67635. })(BABYLON || (BABYLON = {}));
  67636. //# sourceMappingURL=babylon.filesInput.js.map
  67637. var BABYLON;
  67638. (function (BABYLON) {
  67639. /**
  67640. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67641. * The underlying implementation relies on an associative array to ensure the best performances.
  67642. * The value can be anything including 'null' but except 'undefined'
  67643. */
  67644. var StringDictionary = /** @class */ (function () {
  67645. function StringDictionary() {
  67646. this._count = 0;
  67647. this._data = {};
  67648. }
  67649. /**
  67650. * This will clear this dictionary and copy the content from the 'source' one.
  67651. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67652. * @param source the dictionary to take the content from and copy to this dictionary
  67653. */
  67654. StringDictionary.prototype.copyFrom = function (source) {
  67655. var _this = this;
  67656. this.clear();
  67657. source.forEach(function (t, v) { return _this.add(t, v); });
  67658. };
  67659. /**
  67660. * Get a value based from its key
  67661. * @param key the given key to get the matching value from
  67662. * @return the value if found, otherwise undefined is returned
  67663. */
  67664. StringDictionary.prototype.get = function (key) {
  67665. var val = this._data[key];
  67666. if (val !== undefined) {
  67667. return val;
  67668. }
  67669. return undefined;
  67670. };
  67671. /**
  67672. * Get a value from its key or add it if it doesn't exist.
  67673. * This method will ensure you that a given key/data will be present in the dictionary.
  67674. * @param key the given key to get the matching value from
  67675. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67676. * The factory will only be invoked if there's no data for the given key.
  67677. * @return the value corresponding to the key.
  67678. */
  67679. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67680. var val = this.get(key);
  67681. if (val !== undefined) {
  67682. return val;
  67683. }
  67684. val = factory(key);
  67685. if (val) {
  67686. this.add(key, val);
  67687. }
  67688. return val;
  67689. };
  67690. /**
  67691. * Get a value from its key if present in the dictionary otherwise add it
  67692. * @param key the key to get the value from
  67693. * @param val if there's no such key/value pair in the dictionary add it with this value
  67694. * @return the value corresponding to the key
  67695. */
  67696. StringDictionary.prototype.getOrAdd = function (key, val) {
  67697. var curVal = this.get(key);
  67698. if (curVal !== undefined) {
  67699. return curVal;
  67700. }
  67701. this.add(key, val);
  67702. return val;
  67703. };
  67704. /**
  67705. * Check if there's a given key in the dictionary
  67706. * @param key the key to check for
  67707. * @return true if the key is present, false otherwise
  67708. */
  67709. StringDictionary.prototype.contains = function (key) {
  67710. return this._data[key] !== undefined;
  67711. };
  67712. /**
  67713. * Add a new key and its corresponding value
  67714. * @param key the key to add
  67715. * @param value the value corresponding to the key
  67716. * @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
  67717. */
  67718. StringDictionary.prototype.add = function (key, value) {
  67719. if (this._data[key] !== undefined) {
  67720. return false;
  67721. }
  67722. this._data[key] = value;
  67723. ++this._count;
  67724. return true;
  67725. };
  67726. StringDictionary.prototype.set = function (key, value) {
  67727. if (this._data[key] === undefined) {
  67728. return false;
  67729. }
  67730. this._data[key] = value;
  67731. return true;
  67732. };
  67733. /**
  67734. * Get the element of the given key and remove it from the dictionary
  67735. * @param key
  67736. */
  67737. StringDictionary.prototype.getAndRemove = function (key) {
  67738. var val = this.get(key);
  67739. if (val !== undefined) {
  67740. delete this._data[key];
  67741. --this._count;
  67742. return val;
  67743. }
  67744. return null;
  67745. };
  67746. /**
  67747. * Remove a key/value from the dictionary.
  67748. * @param key the key to remove
  67749. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67750. */
  67751. StringDictionary.prototype.remove = function (key) {
  67752. if (this.contains(key)) {
  67753. delete this._data[key];
  67754. --this._count;
  67755. return true;
  67756. }
  67757. return false;
  67758. };
  67759. /**
  67760. * Clear the whole content of the dictionary
  67761. */
  67762. StringDictionary.prototype.clear = function () {
  67763. this._data = {};
  67764. this._count = 0;
  67765. };
  67766. Object.defineProperty(StringDictionary.prototype, "count", {
  67767. get: function () {
  67768. return this._count;
  67769. },
  67770. enumerable: true,
  67771. configurable: true
  67772. });
  67773. /**
  67774. * Execute a callback on each key/val of the dictionary.
  67775. * Note that you can remove any element in this dictionary in the callback implementation
  67776. * @param callback the callback to execute on a given key/value pair
  67777. */
  67778. StringDictionary.prototype.forEach = function (callback) {
  67779. for (var cur in this._data) {
  67780. var val = this._data[cur];
  67781. callback(cur, val);
  67782. }
  67783. };
  67784. /**
  67785. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67786. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67787. * Note that you can remove any element in this dictionary in the callback implementation
  67788. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67789. */
  67790. StringDictionary.prototype.first = function (callback) {
  67791. for (var cur in this._data) {
  67792. var val = this._data[cur];
  67793. var res = callback(cur, val);
  67794. if (res) {
  67795. return res;
  67796. }
  67797. }
  67798. return null;
  67799. };
  67800. return StringDictionary;
  67801. }());
  67802. BABYLON.StringDictionary = StringDictionary;
  67803. })(BABYLON || (BABYLON = {}));
  67804. //# sourceMappingURL=babylon.stringDictionary.js.map
  67805. var BABYLON;
  67806. (function (BABYLON) {
  67807. var Tags = /** @class */ (function () {
  67808. function Tags() {
  67809. }
  67810. Tags.EnableFor = function (obj) {
  67811. obj._tags = obj._tags || {};
  67812. obj.hasTags = function () {
  67813. return Tags.HasTags(obj);
  67814. };
  67815. obj.addTags = function (tagsString) {
  67816. return Tags.AddTagsTo(obj, tagsString);
  67817. };
  67818. obj.removeTags = function (tagsString) {
  67819. return Tags.RemoveTagsFrom(obj, tagsString);
  67820. };
  67821. obj.matchesTagsQuery = function (tagsQuery) {
  67822. return Tags.MatchesQuery(obj, tagsQuery);
  67823. };
  67824. };
  67825. Tags.DisableFor = function (obj) {
  67826. delete obj._tags;
  67827. delete obj.hasTags;
  67828. delete obj.addTags;
  67829. delete obj.removeTags;
  67830. delete obj.matchesTagsQuery;
  67831. };
  67832. Tags.HasTags = function (obj) {
  67833. if (!obj._tags) {
  67834. return false;
  67835. }
  67836. return !BABYLON.Tools.IsEmpty(obj._tags);
  67837. };
  67838. Tags.GetTags = function (obj, asString) {
  67839. if (asString === void 0) { asString = true; }
  67840. if (!obj._tags) {
  67841. return null;
  67842. }
  67843. if (asString) {
  67844. var tagsArray = [];
  67845. for (var tag in obj._tags) {
  67846. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67847. tagsArray.push(tag);
  67848. }
  67849. }
  67850. return tagsArray.join(" ");
  67851. }
  67852. else {
  67853. return obj._tags;
  67854. }
  67855. };
  67856. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67857. // a tag cannot start with '||', '&&', and '!'
  67858. // it cannot contain whitespaces
  67859. Tags.AddTagsTo = function (obj, tagsString) {
  67860. if (!tagsString) {
  67861. return;
  67862. }
  67863. if (typeof tagsString !== "string") {
  67864. return;
  67865. }
  67866. var tags = tagsString.split(" ");
  67867. tags.forEach(function (tag, index, array) {
  67868. Tags._AddTagTo(obj, tag);
  67869. });
  67870. };
  67871. Tags._AddTagTo = function (obj, tag) {
  67872. tag = tag.trim();
  67873. if (tag === "" || tag === "true" || tag === "false") {
  67874. return;
  67875. }
  67876. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67877. return;
  67878. }
  67879. Tags.EnableFor(obj);
  67880. obj._tags[tag] = true;
  67881. };
  67882. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67883. if (!Tags.HasTags(obj)) {
  67884. return;
  67885. }
  67886. var tags = tagsString.split(" ");
  67887. for (var t in tags) {
  67888. Tags._RemoveTagFrom(obj, tags[t]);
  67889. }
  67890. };
  67891. Tags._RemoveTagFrom = function (obj, tag) {
  67892. delete obj._tags[tag];
  67893. };
  67894. Tags.MatchesQuery = function (obj, tagsQuery) {
  67895. if (tagsQuery === undefined) {
  67896. return true;
  67897. }
  67898. if (tagsQuery === "") {
  67899. return Tags.HasTags(obj);
  67900. }
  67901. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67902. };
  67903. return Tags;
  67904. }());
  67905. BABYLON.Tags = Tags;
  67906. })(BABYLON || (BABYLON = {}));
  67907. //# sourceMappingURL=babylon.tags.js.map
  67908. var BABYLON;
  67909. (function (BABYLON) {
  67910. var AndOrNotEvaluator = /** @class */ (function () {
  67911. function AndOrNotEvaluator() {
  67912. }
  67913. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67914. if (!query.match(/\([^\(\)]*\)/g)) {
  67915. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67916. }
  67917. else {
  67918. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67919. // remove parenthesis
  67920. r = r.slice(1, r.length - 1);
  67921. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67922. });
  67923. }
  67924. if (query === "true") {
  67925. return true;
  67926. }
  67927. if (query === "false") {
  67928. return false;
  67929. }
  67930. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67931. };
  67932. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67933. evaluateCallback = evaluateCallback || (function (r) {
  67934. return r === "true" ? true : false;
  67935. });
  67936. var result;
  67937. var or = parenthesisContent.split("||");
  67938. for (var i in or) {
  67939. if (or.hasOwnProperty(i)) {
  67940. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  67941. var and = ori.split("&&");
  67942. if (and.length > 1) {
  67943. for (var j = 0; j < and.length; ++j) {
  67944. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  67945. if (andj !== "true" && andj !== "false") {
  67946. if (andj[0] === "!") {
  67947. result = !evaluateCallback(andj.substring(1));
  67948. }
  67949. else {
  67950. result = evaluateCallback(andj);
  67951. }
  67952. }
  67953. else {
  67954. result = andj === "true" ? true : false;
  67955. }
  67956. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  67957. ori = "false";
  67958. break;
  67959. }
  67960. }
  67961. }
  67962. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  67963. result = true;
  67964. break;
  67965. }
  67966. // result equals false (or undefined)
  67967. if (ori !== "true" && ori !== "false") {
  67968. if (ori[0] === "!") {
  67969. result = !evaluateCallback(ori.substring(1));
  67970. }
  67971. else {
  67972. result = evaluateCallback(ori);
  67973. }
  67974. }
  67975. else {
  67976. result = ori === "true" ? true : false;
  67977. }
  67978. }
  67979. }
  67980. // the whole parenthesis scope is replaced by 'true' or 'false'
  67981. return result ? "true" : "false";
  67982. };
  67983. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  67984. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  67985. // remove whitespaces
  67986. r = r.replace(/[\s]/g, function () { return ""; });
  67987. return r.length % 2 ? "!" : "";
  67988. });
  67989. booleanString = booleanString.trim();
  67990. if (booleanString === "!true") {
  67991. booleanString = "false";
  67992. }
  67993. else if (booleanString === "!false") {
  67994. booleanString = "true";
  67995. }
  67996. return booleanString;
  67997. };
  67998. return AndOrNotEvaluator;
  67999. }());
  68000. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68001. })(BABYLON || (BABYLON = {}));
  68002. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68003. var BABYLON;
  68004. (function (BABYLON) {
  68005. var Database = /** @class */ (function () {
  68006. function Database(urlToScene, callbackManifestChecked) {
  68007. // Handling various flavors of prefixed version of IndexedDB
  68008. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68009. this.callbackManifestChecked = callbackManifestChecked;
  68010. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  68011. this.db = null;
  68012. this._enableSceneOffline = false;
  68013. this._enableTexturesOffline = false;
  68014. this.manifestVersionFound = 0;
  68015. this.mustUpdateRessources = false;
  68016. this.hasReachedQuota = false;
  68017. if (!Database.IDBStorageEnabled) {
  68018. this.callbackManifestChecked(true);
  68019. }
  68020. else {
  68021. this.checkManifestFile();
  68022. }
  68023. }
  68024. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68025. get: function () {
  68026. return this._enableSceneOffline;
  68027. },
  68028. enumerable: true,
  68029. configurable: true
  68030. });
  68031. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68032. get: function () {
  68033. return this._enableTexturesOffline;
  68034. },
  68035. enumerable: true,
  68036. configurable: true
  68037. });
  68038. Database.prototype.checkManifestFile = function () {
  68039. var _this = this;
  68040. var noManifestFile = function () {
  68041. _this._enableSceneOffline = false;
  68042. _this._enableTexturesOffline = false;
  68043. _this.callbackManifestChecked(false);
  68044. };
  68045. var timeStampUsed = false;
  68046. var manifestURL = this.currentSceneUrl + ".manifest";
  68047. var xhr = new XMLHttpRequest();
  68048. if (navigator.onLine) {
  68049. // Adding a timestamp to by-pass browsers' cache
  68050. timeStampUsed = true;
  68051. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  68052. }
  68053. xhr.open("GET", manifestURL, true);
  68054. xhr.addEventListener("load", function () {
  68055. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68056. try {
  68057. var manifestFile = JSON.parse(xhr.response);
  68058. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68059. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68060. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68061. _this.manifestVersionFound = manifestFile.version;
  68062. }
  68063. if (_this.callbackManifestChecked) {
  68064. _this.callbackManifestChecked(true);
  68065. }
  68066. }
  68067. catch (ex) {
  68068. noManifestFile();
  68069. }
  68070. }
  68071. else {
  68072. noManifestFile();
  68073. }
  68074. }, false);
  68075. xhr.addEventListener("error", function (event) {
  68076. if (timeStampUsed) {
  68077. timeStampUsed = false;
  68078. // Let's retry without the timeStamp
  68079. // It could fail when coupled with HTML5 Offline API
  68080. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68081. xhr.open("GET", retryManifestURL, true);
  68082. xhr.send();
  68083. }
  68084. else {
  68085. noManifestFile();
  68086. }
  68087. }, false);
  68088. try {
  68089. xhr.send();
  68090. }
  68091. catch (ex) {
  68092. BABYLON.Tools.Error("Error on XHR send request.");
  68093. this.callbackManifestChecked(false);
  68094. }
  68095. };
  68096. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68097. var _this = this;
  68098. var handleError = function () {
  68099. _this.isSupported = false;
  68100. if (errorCallback)
  68101. errorCallback();
  68102. };
  68103. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68104. // Your browser doesn't support IndexedDB
  68105. this.isSupported = false;
  68106. if (errorCallback)
  68107. errorCallback();
  68108. }
  68109. else {
  68110. // If the DB hasn't been opened or created yet
  68111. if (!this.db) {
  68112. this.hasReachedQuota = false;
  68113. this.isSupported = true;
  68114. var request = this.idbFactory.open("babylonjs", 1);
  68115. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68116. request.onerror = function (event) {
  68117. handleError();
  68118. };
  68119. // executes when a version change transaction cannot complete due to other active transactions
  68120. request.onblocked = function (event) {
  68121. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68122. handleError();
  68123. };
  68124. // DB has been opened successfully
  68125. request.onsuccess = function (event) {
  68126. _this.db = request.result;
  68127. successCallback();
  68128. };
  68129. // Initialization of the DB. Creating Scenes & Textures stores
  68130. request.onupgradeneeded = function (event) {
  68131. _this.db = (event.target).result;
  68132. if (_this.db) {
  68133. try {
  68134. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68135. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68136. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68137. }
  68138. catch (ex) {
  68139. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68140. handleError();
  68141. }
  68142. }
  68143. };
  68144. }
  68145. // DB has already been created and opened
  68146. else {
  68147. if (successCallback)
  68148. successCallback();
  68149. }
  68150. }
  68151. };
  68152. Database.prototype.loadImageFromDB = function (url, image) {
  68153. var _this = this;
  68154. var completeURL = Database.ReturnFullUrlLocation(url);
  68155. var saveAndLoadImage = function () {
  68156. if (!_this.hasReachedQuota && _this.db !== null) {
  68157. // the texture is not yet in the DB, let's try to save it
  68158. _this._saveImageIntoDBAsync(completeURL, image);
  68159. }
  68160. // If the texture is not in the DB and we've reached the DB quota limit
  68161. // let's load it directly from the web
  68162. else {
  68163. image.src = url;
  68164. }
  68165. };
  68166. if (!this.mustUpdateRessources) {
  68167. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68168. }
  68169. // First time we're download the images or update requested in the manifest file by a version change
  68170. else {
  68171. saveAndLoadImage();
  68172. }
  68173. };
  68174. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68175. if (this.isSupported && this.db !== null) {
  68176. var texture;
  68177. var transaction = this.db.transaction(["textures"]);
  68178. transaction.onabort = function (event) {
  68179. image.src = url;
  68180. };
  68181. transaction.oncomplete = function (event) {
  68182. var blobTextureURL;
  68183. if (texture) {
  68184. var URL = window.URL || window.webkitURL;
  68185. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68186. image.onerror = function () {
  68187. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68188. image.src = url;
  68189. };
  68190. image.src = blobTextureURL;
  68191. }
  68192. else {
  68193. notInDBCallback();
  68194. }
  68195. };
  68196. var getRequest = transaction.objectStore("textures").get(url);
  68197. getRequest.onsuccess = function (event) {
  68198. texture = (event.target).result;
  68199. };
  68200. getRequest.onerror = function (event) {
  68201. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68202. image.src = url;
  68203. };
  68204. }
  68205. else {
  68206. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68207. image.src = url;
  68208. }
  68209. };
  68210. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68211. var _this = this;
  68212. if (this.isSupported) {
  68213. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68214. var generateBlobUrl = function () {
  68215. var blobTextureURL;
  68216. if (blob) {
  68217. var URL = window.URL || window.webkitURL;
  68218. try {
  68219. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68220. }
  68221. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68222. catch (ex) {
  68223. blobTextureURL = URL.createObjectURL(blob);
  68224. }
  68225. }
  68226. if (blobTextureURL) {
  68227. image.src = blobTextureURL;
  68228. }
  68229. };
  68230. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68231. var xhr = new XMLHttpRequest(), blob;
  68232. xhr.open("GET", url, true);
  68233. xhr.responseType = "blob";
  68234. xhr.addEventListener("load", function () {
  68235. if (xhr.status === 200 && _this.db) {
  68236. // Blob as response (XHR2)
  68237. blob = xhr.response;
  68238. var transaction = _this.db.transaction(["textures"], "readwrite");
  68239. // the transaction could abort because of a QuotaExceededError error
  68240. transaction.onabort = function (event) {
  68241. try {
  68242. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68243. var srcElement = (event.srcElement || event.target);
  68244. var error = srcElement.error;
  68245. if (error && error.name === "QuotaExceededError") {
  68246. _this.hasReachedQuota = true;
  68247. }
  68248. }
  68249. catch (ex) { }
  68250. generateBlobUrl();
  68251. };
  68252. transaction.oncomplete = function (event) {
  68253. generateBlobUrl();
  68254. };
  68255. var newTexture = { textureUrl: url, data: blob };
  68256. try {
  68257. // Put the blob into the dabase
  68258. var addRequest = transaction.objectStore("textures").put(newTexture);
  68259. addRequest.onsuccess = function (event) {
  68260. };
  68261. addRequest.onerror = function (event) {
  68262. generateBlobUrl();
  68263. };
  68264. }
  68265. catch (ex) {
  68266. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68267. if (ex.code === 25) {
  68268. Database.IsUASupportingBlobStorage = false;
  68269. }
  68270. image.src = url;
  68271. }
  68272. }
  68273. else {
  68274. image.src = url;
  68275. }
  68276. }, false);
  68277. xhr.addEventListener("error", function (event) {
  68278. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68279. image.src = url;
  68280. }, false);
  68281. xhr.send();
  68282. }
  68283. else {
  68284. image.src = url;
  68285. }
  68286. }
  68287. else {
  68288. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68289. image.src = url;
  68290. }
  68291. };
  68292. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68293. var _this = this;
  68294. var updateVersion = function () {
  68295. // the version is not yet in the DB or we need to update it
  68296. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68297. };
  68298. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68299. };
  68300. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68301. var _this = this;
  68302. if (this.isSupported && this.db) {
  68303. var version;
  68304. try {
  68305. var transaction = this.db.transaction(["versions"]);
  68306. transaction.oncomplete = function (event) {
  68307. if (version) {
  68308. // If the version in the JSON file is > than the version in DB
  68309. if (_this.manifestVersionFound > version.data) {
  68310. _this.mustUpdateRessources = true;
  68311. updateInDBCallback();
  68312. }
  68313. else {
  68314. callback(version.data);
  68315. }
  68316. }
  68317. // version was not found in DB
  68318. else {
  68319. _this.mustUpdateRessources = true;
  68320. updateInDBCallback();
  68321. }
  68322. };
  68323. transaction.onabort = function (event) {
  68324. callback(-1);
  68325. };
  68326. var getRequest = transaction.objectStore("versions").get(url);
  68327. getRequest.onsuccess = function (event) {
  68328. version = (event.target).result;
  68329. };
  68330. getRequest.onerror = function (event) {
  68331. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68332. callback(-1);
  68333. };
  68334. }
  68335. catch (ex) {
  68336. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68337. callback(-1);
  68338. }
  68339. }
  68340. else {
  68341. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68342. callback(-1);
  68343. }
  68344. };
  68345. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68346. var _this = this;
  68347. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68348. try {
  68349. // Open a transaction to the database
  68350. var transaction = this.db.transaction(["versions"], "readwrite");
  68351. // the transaction could abort because of a QuotaExceededError error
  68352. transaction.onabort = function (event) {
  68353. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68354. var error = event.srcElement['error'];
  68355. if (error && error.name === "QuotaExceededError") {
  68356. _this.hasReachedQuota = true;
  68357. }
  68358. }
  68359. catch (ex) { }
  68360. callback(-1);
  68361. };
  68362. transaction.oncomplete = function (event) {
  68363. callback(_this.manifestVersionFound);
  68364. };
  68365. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68366. // Put the scene into the database
  68367. var addRequest = transaction.objectStore("versions").put(newVersion);
  68368. addRequest.onsuccess = function (event) {
  68369. };
  68370. addRequest.onerror = function (event) {
  68371. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68372. };
  68373. }
  68374. catch (ex) {
  68375. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68376. callback(-1);
  68377. }
  68378. }
  68379. else {
  68380. callback(-1);
  68381. }
  68382. };
  68383. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68384. var _this = this;
  68385. var completeUrl = Database.ReturnFullUrlLocation(url);
  68386. var saveAndLoadFile = function () {
  68387. // the scene is not yet in the DB, let's try to save it
  68388. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68389. };
  68390. this._checkVersionFromDB(completeUrl, function (version) {
  68391. if (version !== -1) {
  68392. if (!_this.mustUpdateRessources) {
  68393. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68394. }
  68395. else {
  68396. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68397. }
  68398. }
  68399. else {
  68400. if (errorCallback) {
  68401. errorCallback();
  68402. }
  68403. }
  68404. });
  68405. };
  68406. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68407. if (this.isSupported && this.db) {
  68408. var targetStore;
  68409. if (url.indexOf(".babylon") !== -1) {
  68410. targetStore = "scenes";
  68411. }
  68412. else {
  68413. targetStore = "textures";
  68414. }
  68415. var file;
  68416. var transaction = this.db.transaction([targetStore]);
  68417. transaction.oncomplete = function (event) {
  68418. if (file) {
  68419. callback(file.data);
  68420. }
  68421. // file was not found in DB
  68422. else {
  68423. notInDBCallback();
  68424. }
  68425. };
  68426. transaction.onabort = function (event) {
  68427. notInDBCallback();
  68428. };
  68429. var getRequest = transaction.objectStore(targetStore).get(url);
  68430. getRequest.onsuccess = function (event) {
  68431. file = (event.target).result;
  68432. };
  68433. getRequest.onerror = function (event) {
  68434. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68435. notInDBCallback();
  68436. };
  68437. }
  68438. else {
  68439. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68440. callback();
  68441. }
  68442. };
  68443. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68444. var _this = this;
  68445. if (this.isSupported) {
  68446. var targetStore;
  68447. if (url.indexOf(".babylon") !== -1) {
  68448. targetStore = "scenes";
  68449. }
  68450. else {
  68451. targetStore = "textures";
  68452. }
  68453. // Create XHR
  68454. var xhr = new XMLHttpRequest();
  68455. var fileData;
  68456. xhr.open("GET", url, true);
  68457. if (useArrayBuffer) {
  68458. xhr.responseType = "arraybuffer";
  68459. }
  68460. if (progressCallback) {
  68461. xhr.onprogress = progressCallback;
  68462. }
  68463. xhr.addEventListener("load", function () {
  68464. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68465. // Blob as response (XHR2)
  68466. //fileData = xhr.responseText;
  68467. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68468. if (!_this.hasReachedQuota && _this.db) {
  68469. // Open a transaction to the database
  68470. var transaction = _this.db.transaction([targetStore], "readwrite");
  68471. // the transaction could abort because of a QuotaExceededError error
  68472. transaction.onabort = function (event) {
  68473. try {
  68474. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68475. var error = event.srcElement['error'];
  68476. if (error && error.name === "QuotaExceededError") {
  68477. _this.hasReachedQuota = true;
  68478. }
  68479. }
  68480. catch (ex) { }
  68481. callback(fileData);
  68482. };
  68483. transaction.oncomplete = function (event) {
  68484. callback(fileData);
  68485. };
  68486. var newFile;
  68487. if (targetStore === "scenes") {
  68488. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68489. }
  68490. else {
  68491. newFile = { textureUrl: url, data: fileData };
  68492. }
  68493. try {
  68494. // Put the scene into the database
  68495. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68496. addRequest.onsuccess = function (event) {
  68497. };
  68498. addRequest.onerror = function (event) {
  68499. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68500. };
  68501. }
  68502. catch (ex) {
  68503. callback(fileData);
  68504. }
  68505. }
  68506. else {
  68507. callback(fileData);
  68508. }
  68509. }
  68510. else {
  68511. callback();
  68512. }
  68513. }, false);
  68514. xhr.addEventListener("error", function (event) {
  68515. BABYLON.Tools.Error("error on XHR request.");
  68516. callback();
  68517. }, false);
  68518. xhr.send();
  68519. }
  68520. else {
  68521. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68522. callback();
  68523. }
  68524. };
  68525. Database.IsUASupportingBlobStorage = true;
  68526. Database.IDBStorageEnabled = true;
  68527. Database.parseURL = function (url) {
  68528. var a = document.createElement('a');
  68529. a.href = url;
  68530. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68531. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68532. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68533. return absLocation;
  68534. };
  68535. Database.ReturnFullUrlLocation = function (url) {
  68536. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68537. return (Database.parseURL(window.location.href) + url);
  68538. }
  68539. else {
  68540. return url;
  68541. }
  68542. };
  68543. return Database;
  68544. }());
  68545. BABYLON.Database = Database;
  68546. })(BABYLON || (BABYLON = {}));
  68547. //# sourceMappingURL=babylon.database.js.map
  68548. var BABYLON;
  68549. (function (BABYLON) {
  68550. var FresnelParameters = /** @class */ (function () {
  68551. function FresnelParameters() {
  68552. this._isEnabled = true;
  68553. this.leftColor = BABYLON.Color3.White();
  68554. this.rightColor = BABYLON.Color3.Black();
  68555. this.bias = 0;
  68556. this.power = 1;
  68557. }
  68558. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68559. get: function () {
  68560. return this._isEnabled;
  68561. },
  68562. set: function (value) {
  68563. if (this._isEnabled === value) {
  68564. return;
  68565. }
  68566. this._isEnabled = value;
  68567. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68568. },
  68569. enumerable: true,
  68570. configurable: true
  68571. });
  68572. FresnelParameters.prototype.clone = function () {
  68573. var newFresnelParameters = new FresnelParameters();
  68574. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68575. return newFresnelParameters;
  68576. };
  68577. FresnelParameters.prototype.serialize = function () {
  68578. var serializationObject = {};
  68579. serializationObject.isEnabled = this.isEnabled;
  68580. serializationObject.leftColor = this.leftColor.asArray();
  68581. serializationObject.rightColor = this.rightColor.asArray();
  68582. serializationObject.bias = this.bias;
  68583. serializationObject.power = this.power;
  68584. return serializationObject;
  68585. };
  68586. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68587. var fresnelParameters = new FresnelParameters();
  68588. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68589. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68590. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68591. fresnelParameters.bias = parsedFresnelParameters.bias;
  68592. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68593. return fresnelParameters;
  68594. };
  68595. return FresnelParameters;
  68596. }());
  68597. BABYLON.FresnelParameters = FresnelParameters;
  68598. })(BABYLON || (BABYLON = {}));
  68599. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68600. var BABYLON;
  68601. (function (BABYLON) {
  68602. var MultiMaterial = /** @class */ (function (_super) {
  68603. __extends(MultiMaterial, _super);
  68604. function MultiMaterial(name, scene) {
  68605. var _this = _super.call(this, name, scene, true) || this;
  68606. scene.multiMaterials.push(_this);
  68607. _this.subMaterials = new Array();
  68608. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68609. return _this;
  68610. }
  68611. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68612. get: function () {
  68613. return this._subMaterials;
  68614. },
  68615. set: function (value) {
  68616. this._subMaterials = value;
  68617. this._hookArray(value);
  68618. },
  68619. enumerable: true,
  68620. configurable: true
  68621. });
  68622. MultiMaterial.prototype._hookArray = function (array) {
  68623. var _this = this;
  68624. var oldPush = array.push;
  68625. array.push = function () {
  68626. var items = [];
  68627. for (var _i = 0; _i < arguments.length; _i++) {
  68628. items[_i] = arguments[_i];
  68629. }
  68630. var result = oldPush.apply(array, items);
  68631. _this._markAllSubMeshesAsTexturesDirty();
  68632. return result;
  68633. };
  68634. var oldSplice = array.splice;
  68635. array.splice = function (index, deleteCount) {
  68636. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68637. _this._markAllSubMeshesAsTexturesDirty();
  68638. return deleted;
  68639. };
  68640. };
  68641. // Properties
  68642. MultiMaterial.prototype.getSubMaterial = function (index) {
  68643. if (index < 0 || index >= this.subMaterials.length) {
  68644. return this.getScene().defaultMaterial;
  68645. }
  68646. return this.subMaterials[index];
  68647. };
  68648. MultiMaterial.prototype.getActiveTextures = function () {
  68649. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68650. if (subMaterial) {
  68651. return subMaterial.getActiveTextures();
  68652. }
  68653. else {
  68654. return [];
  68655. }
  68656. }));
  68657. var _a;
  68658. };
  68659. // Methods
  68660. MultiMaterial.prototype.getClassName = function () {
  68661. return "MultiMaterial";
  68662. };
  68663. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68664. for (var index = 0; index < this.subMaterials.length; index++) {
  68665. var subMaterial = this.subMaterials[index];
  68666. if (subMaterial) {
  68667. if (subMaterial.storeEffectOnSubMeshes) {
  68668. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68669. return false;
  68670. }
  68671. continue;
  68672. }
  68673. if (!subMaterial.isReady(mesh)) {
  68674. return false;
  68675. }
  68676. }
  68677. }
  68678. return true;
  68679. };
  68680. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68681. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68682. for (var index = 0; index < this.subMaterials.length; index++) {
  68683. var subMaterial = null;
  68684. var current = this.subMaterials[index];
  68685. if (cloneChildren && current) {
  68686. subMaterial = current.clone(name + "-" + current.name);
  68687. }
  68688. else {
  68689. subMaterial = this.subMaterials[index];
  68690. }
  68691. newMultiMaterial.subMaterials.push(subMaterial);
  68692. }
  68693. return newMultiMaterial;
  68694. };
  68695. MultiMaterial.prototype.serialize = function () {
  68696. var serializationObject = {};
  68697. serializationObject.name = this.name;
  68698. serializationObject.id = this.id;
  68699. if (BABYLON.Tags) {
  68700. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68701. }
  68702. serializationObject.materials = [];
  68703. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68704. var subMat = this.subMaterials[matIndex];
  68705. if (subMat) {
  68706. serializationObject.materials.push(subMat.id);
  68707. }
  68708. else {
  68709. serializationObject.materials.push(null);
  68710. }
  68711. }
  68712. return serializationObject;
  68713. };
  68714. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68715. var scene = this.getScene();
  68716. if (!scene) {
  68717. return;
  68718. }
  68719. var index = scene.multiMaterials.indexOf(this);
  68720. if (index >= 0) {
  68721. scene.multiMaterials.splice(index, 1);
  68722. }
  68723. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68724. };
  68725. return MultiMaterial;
  68726. }(BABYLON.Material));
  68727. BABYLON.MultiMaterial = MultiMaterial;
  68728. })(BABYLON || (BABYLON = {}));
  68729. //# sourceMappingURL=babylon.multiMaterial.js.map
  68730. var BABYLON;
  68731. (function (BABYLON) {
  68732. var FreeCameraTouchInput = /** @class */ (function () {
  68733. function FreeCameraTouchInput() {
  68734. this._offsetX = null;
  68735. this._offsetY = null;
  68736. this._pointerPressed = new Array();
  68737. this.touchAngularSensibility = 200000.0;
  68738. this.touchMoveSensibility = 250.0;
  68739. }
  68740. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68741. var _this = this;
  68742. var previousPosition = null;
  68743. if (this._pointerInput === undefined) {
  68744. this._onLostFocus = function (evt) {
  68745. _this._offsetX = null;
  68746. _this._offsetY = null;
  68747. };
  68748. this._pointerInput = function (p, s) {
  68749. var evt = p.event;
  68750. if (evt.pointerType === "mouse") {
  68751. return;
  68752. }
  68753. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68754. if (!noPreventDefault) {
  68755. evt.preventDefault();
  68756. }
  68757. _this._pointerPressed.push(evt.pointerId);
  68758. if (_this._pointerPressed.length !== 1) {
  68759. return;
  68760. }
  68761. previousPosition = {
  68762. x: evt.clientX,
  68763. y: evt.clientY
  68764. };
  68765. }
  68766. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68767. if (!noPreventDefault) {
  68768. evt.preventDefault();
  68769. }
  68770. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68771. if (index === -1) {
  68772. return;
  68773. }
  68774. _this._pointerPressed.splice(index, 1);
  68775. if (index != 0) {
  68776. return;
  68777. }
  68778. previousPosition = null;
  68779. _this._offsetX = null;
  68780. _this._offsetY = null;
  68781. }
  68782. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68783. if (!noPreventDefault) {
  68784. evt.preventDefault();
  68785. }
  68786. if (!previousPosition) {
  68787. return;
  68788. }
  68789. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68790. if (index != 0) {
  68791. return;
  68792. }
  68793. _this._offsetX = evt.clientX - previousPosition.x;
  68794. _this._offsetY = -(evt.clientY - previousPosition.y);
  68795. }
  68796. };
  68797. }
  68798. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68799. if (this._onLostFocus) {
  68800. element.addEventListener("blur", this._onLostFocus);
  68801. }
  68802. };
  68803. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68804. if (this._pointerInput && element) {
  68805. if (this._observer) {
  68806. this.camera.getScene().onPointerObservable.remove(this._observer);
  68807. this._observer = null;
  68808. }
  68809. if (this._onLostFocus) {
  68810. element.removeEventListener("blur", this._onLostFocus);
  68811. this._onLostFocus = null;
  68812. }
  68813. this._pointerPressed = [];
  68814. this._offsetX = null;
  68815. this._offsetY = null;
  68816. }
  68817. };
  68818. FreeCameraTouchInput.prototype.checkInputs = function () {
  68819. if (this._offsetX && this._offsetY) {
  68820. var camera = this.camera;
  68821. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68822. if (this._pointerPressed.length > 1) {
  68823. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68824. }
  68825. else {
  68826. var speed = camera._computeLocalCameraSpeed();
  68827. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68828. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68829. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68830. }
  68831. }
  68832. };
  68833. FreeCameraTouchInput.prototype.getClassName = function () {
  68834. return "FreeCameraTouchInput";
  68835. };
  68836. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68837. return "touch";
  68838. };
  68839. __decorate([
  68840. BABYLON.serialize()
  68841. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68842. __decorate([
  68843. BABYLON.serialize()
  68844. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68845. return FreeCameraTouchInput;
  68846. }());
  68847. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68848. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68849. })(BABYLON || (BABYLON = {}));
  68850. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68851. var BABYLON;
  68852. (function (BABYLON) {
  68853. // We're mainly based on the logic defined into the FreeCamera code
  68854. var TouchCamera = /** @class */ (function (_super) {
  68855. __extends(TouchCamera, _super);
  68856. //-- end properties for backward compatibility for inputs
  68857. function TouchCamera(name, position, scene) {
  68858. var _this = _super.call(this, name, position, scene) || this;
  68859. _this.inputs.addTouch();
  68860. _this._setupInputs();
  68861. return _this;
  68862. }
  68863. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68864. //-- Begin properties for backward compatibility for inputs
  68865. get: function () {
  68866. var touch = this.inputs.attached["touch"];
  68867. if (touch)
  68868. return touch.touchAngularSensibility;
  68869. return 0;
  68870. },
  68871. set: function (value) {
  68872. var touch = this.inputs.attached["touch"];
  68873. if (touch)
  68874. touch.touchAngularSensibility = value;
  68875. },
  68876. enumerable: true,
  68877. configurable: true
  68878. });
  68879. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68880. get: function () {
  68881. var touch = this.inputs.attached["touch"];
  68882. if (touch)
  68883. return touch.touchMoveSensibility;
  68884. return 0;
  68885. },
  68886. set: function (value) {
  68887. var touch = this.inputs.attached["touch"];
  68888. if (touch)
  68889. touch.touchMoveSensibility = value;
  68890. },
  68891. enumerable: true,
  68892. configurable: true
  68893. });
  68894. TouchCamera.prototype.getClassName = function () {
  68895. return "TouchCamera";
  68896. };
  68897. TouchCamera.prototype._setupInputs = function () {
  68898. var mouse = this.inputs.attached["mouse"];
  68899. if (mouse) {
  68900. mouse.touchEnabled = false;
  68901. }
  68902. };
  68903. return TouchCamera;
  68904. }(BABYLON.FreeCamera));
  68905. BABYLON.TouchCamera = TouchCamera;
  68906. })(BABYLON || (BABYLON = {}));
  68907. //# sourceMappingURL=babylon.touchCamera.js.map
  68908. var BABYLON;
  68909. (function (BABYLON) {
  68910. var ProceduralTexture = /** @class */ (function (_super) {
  68911. __extends(ProceduralTexture, _super);
  68912. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68913. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68914. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68915. if (isCube === void 0) { isCube = false; }
  68916. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68917. _this.isCube = isCube;
  68918. _this.isEnabled = true;
  68919. _this._currentRefreshId = -1;
  68920. _this._refreshRate = 1;
  68921. _this._vertexBuffers = {};
  68922. _this._uniforms = new Array();
  68923. _this._samplers = new Array();
  68924. _this._textures = {};
  68925. _this._floats = {};
  68926. _this._floatsArrays = {};
  68927. _this._colors3 = {};
  68928. _this._colors4 = {};
  68929. _this._vectors2 = {};
  68930. _this._vectors3 = {};
  68931. _this._matrices = {};
  68932. _this._fallbackTextureUsed = false;
  68933. scene.proceduralTextures.push(_this);
  68934. _this._engine = scene.getEngine();
  68935. _this.name = name;
  68936. _this.isRenderTarget = true;
  68937. _this._size = size;
  68938. _this._generateMipMaps = generateMipMaps;
  68939. _this.setFragment(fragment);
  68940. _this._fallbackTexture = fallbackTexture;
  68941. if (isCube) {
  68942. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  68943. _this.setFloat("face", 0);
  68944. }
  68945. else {
  68946. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  68947. }
  68948. // VBO
  68949. var vertices = [];
  68950. vertices.push(1, 1);
  68951. vertices.push(-1, 1);
  68952. vertices.push(-1, -1);
  68953. vertices.push(1, -1);
  68954. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  68955. _this._createIndexBuffer();
  68956. return _this;
  68957. }
  68958. ProceduralTexture.prototype._createIndexBuffer = function () {
  68959. var engine = this._engine;
  68960. // Indices
  68961. var indices = [];
  68962. indices.push(0);
  68963. indices.push(1);
  68964. indices.push(2);
  68965. indices.push(0);
  68966. indices.push(2);
  68967. indices.push(3);
  68968. this._indexBuffer = engine.createIndexBuffer(indices);
  68969. };
  68970. ProceduralTexture.prototype._rebuild = function () {
  68971. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  68972. if (vb) {
  68973. vb._rebuild();
  68974. }
  68975. this._createIndexBuffer();
  68976. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  68977. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  68978. }
  68979. };
  68980. ProceduralTexture.prototype.reset = function () {
  68981. if (this._effect === undefined) {
  68982. return;
  68983. }
  68984. var engine = this._engine;
  68985. engine._releaseEffect(this._effect);
  68986. };
  68987. ProceduralTexture.prototype.isReady = function () {
  68988. var _this = this;
  68989. var engine = this._engine;
  68990. var shaders;
  68991. if (!this._fragment) {
  68992. return false;
  68993. }
  68994. if (this._fallbackTextureUsed) {
  68995. return true;
  68996. }
  68997. if (this._fragment.fragmentElement !== undefined) {
  68998. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  68999. }
  69000. else {
  69001. shaders = { vertex: "procedural", fragment: this._fragment };
  69002. }
  69003. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69004. _this.releaseInternalTexture();
  69005. if (_this._fallbackTexture) {
  69006. _this._texture = _this._fallbackTexture._texture;
  69007. if (_this._texture) {
  69008. _this._texture.incrementReferences();
  69009. }
  69010. }
  69011. _this._fallbackTextureUsed = true;
  69012. });
  69013. return this._effect.isReady();
  69014. };
  69015. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69016. this._currentRefreshId = -1;
  69017. };
  69018. ProceduralTexture.prototype.setFragment = function (fragment) {
  69019. this._fragment = fragment;
  69020. };
  69021. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69022. get: function () {
  69023. return this._refreshRate;
  69024. },
  69025. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69026. set: function (value) {
  69027. this._refreshRate = value;
  69028. this.resetRefreshCounter();
  69029. },
  69030. enumerable: true,
  69031. configurable: true
  69032. });
  69033. ProceduralTexture.prototype._shouldRender = function () {
  69034. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69035. return false;
  69036. }
  69037. if (this._fallbackTextureUsed) {
  69038. return false;
  69039. }
  69040. if (this._currentRefreshId === -1) { // At least render once
  69041. this._currentRefreshId = 1;
  69042. return true;
  69043. }
  69044. if (this.refreshRate === this._currentRefreshId) {
  69045. this._currentRefreshId = 1;
  69046. return true;
  69047. }
  69048. this._currentRefreshId++;
  69049. return false;
  69050. };
  69051. ProceduralTexture.prototype.getRenderSize = function () {
  69052. return this._size;
  69053. };
  69054. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69055. if (this._fallbackTextureUsed) {
  69056. return;
  69057. }
  69058. this.releaseInternalTexture();
  69059. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69060. };
  69061. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69062. if (this._uniforms.indexOf(uniformName) === -1) {
  69063. this._uniforms.push(uniformName);
  69064. }
  69065. };
  69066. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69067. if (this._samplers.indexOf(name) === -1) {
  69068. this._samplers.push(name);
  69069. }
  69070. this._textures[name] = texture;
  69071. return this;
  69072. };
  69073. ProceduralTexture.prototype.setFloat = function (name, value) {
  69074. this._checkUniform(name);
  69075. this._floats[name] = value;
  69076. return this;
  69077. };
  69078. ProceduralTexture.prototype.setFloats = function (name, value) {
  69079. this._checkUniform(name);
  69080. this._floatsArrays[name] = value;
  69081. return this;
  69082. };
  69083. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69084. this._checkUniform(name);
  69085. this._colors3[name] = value;
  69086. return this;
  69087. };
  69088. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69089. this._checkUniform(name);
  69090. this._colors4[name] = value;
  69091. return this;
  69092. };
  69093. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69094. this._checkUniform(name);
  69095. this._vectors2[name] = value;
  69096. return this;
  69097. };
  69098. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69099. this._checkUniform(name);
  69100. this._vectors3[name] = value;
  69101. return this;
  69102. };
  69103. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69104. this._checkUniform(name);
  69105. this._matrices[name] = value;
  69106. return this;
  69107. };
  69108. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69109. var scene = this.getScene();
  69110. if (!scene) {
  69111. return;
  69112. }
  69113. var engine = this._engine;
  69114. // Render
  69115. engine.enableEffect(this._effect);
  69116. engine.setState(false);
  69117. // Texture
  69118. for (var name in this._textures) {
  69119. this._effect.setTexture(name, this._textures[name]);
  69120. }
  69121. // Float
  69122. for (name in this._floats) {
  69123. this._effect.setFloat(name, this._floats[name]);
  69124. }
  69125. // Floats
  69126. for (name in this._floatsArrays) {
  69127. this._effect.setArray(name, this._floatsArrays[name]);
  69128. }
  69129. // Color3
  69130. for (name in this._colors3) {
  69131. this._effect.setColor3(name, this._colors3[name]);
  69132. }
  69133. // Color4
  69134. for (name in this._colors4) {
  69135. var color = this._colors4[name];
  69136. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69137. }
  69138. // Vector2
  69139. for (name in this._vectors2) {
  69140. this._effect.setVector2(name, this._vectors2[name]);
  69141. }
  69142. // Vector3
  69143. for (name in this._vectors3) {
  69144. this._effect.setVector3(name, this._vectors3[name]);
  69145. }
  69146. // Matrix
  69147. for (name in this._matrices) {
  69148. this._effect.setMatrix(name, this._matrices[name]);
  69149. }
  69150. if (!this._texture) {
  69151. return;
  69152. }
  69153. if (this.isCube) {
  69154. for (var face = 0; face < 6; face++) {
  69155. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69156. // VBOs
  69157. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69158. this._effect.setFloat("face", face);
  69159. // Clear
  69160. engine.clear(scene.clearColor, true, true, true);
  69161. // Draw order
  69162. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69163. // Mipmaps
  69164. if (face === 5) {
  69165. engine.generateMipMapsForCubemap(this._texture);
  69166. }
  69167. }
  69168. }
  69169. else {
  69170. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69171. // VBOs
  69172. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69173. // Clear
  69174. engine.clear(scene.clearColor, true, true, true);
  69175. // Draw order
  69176. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69177. }
  69178. // Unbind
  69179. engine.unBindFramebuffer(this._texture, this.isCube);
  69180. if (this.onGenerated) {
  69181. this.onGenerated();
  69182. }
  69183. };
  69184. ProceduralTexture.prototype.clone = function () {
  69185. var textureSize = this.getSize();
  69186. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69187. // Base texture
  69188. newTexture.hasAlpha = this.hasAlpha;
  69189. newTexture.level = this.level;
  69190. // RenderTarget Texture
  69191. newTexture.coordinatesMode = this.coordinatesMode;
  69192. return newTexture;
  69193. };
  69194. ProceduralTexture.prototype.dispose = function () {
  69195. var scene = this.getScene();
  69196. if (!scene) {
  69197. return;
  69198. }
  69199. var index = scene.proceduralTextures.indexOf(this);
  69200. if (index >= 0) {
  69201. scene.proceduralTextures.splice(index, 1);
  69202. }
  69203. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69204. if (vertexBuffer) {
  69205. vertexBuffer.dispose();
  69206. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69207. }
  69208. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69209. this._indexBuffer = null;
  69210. }
  69211. _super.prototype.dispose.call(this);
  69212. };
  69213. return ProceduralTexture;
  69214. }(BABYLON.Texture));
  69215. BABYLON.ProceduralTexture = ProceduralTexture;
  69216. })(BABYLON || (BABYLON = {}));
  69217. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69218. var BABYLON;
  69219. (function (BABYLON) {
  69220. var CustomProceduralTexture = /** @class */ (function (_super) {
  69221. __extends(CustomProceduralTexture, _super);
  69222. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69223. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69224. _this._animate = true;
  69225. _this._time = 0;
  69226. _this._texturePath = texturePath;
  69227. //Try to load json
  69228. _this.loadJson(texturePath);
  69229. _this.refreshRate = 1;
  69230. return _this;
  69231. }
  69232. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69233. var _this = this;
  69234. var noConfigFile = function () {
  69235. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69236. try {
  69237. _this.setFragment(_this._texturePath);
  69238. }
  69239. catch (ex) {
  69240. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69241. }
  69242. };
  69243. var configFileUrl = jsonUrl + "/config.json";
  69244. var xhr = new XMLHttpRequest();
  69245. xhr.open("GET", configFileUrl, true);
  69246. xhr.addEventListener("load", function () {
  69247. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69248. try {
  69249. _this._config = JSON.parse(xhr.response);
  69250. _this.updateShaderUniforms();
  69251. _this.updateTextures();
  69252. _this.setFragment(_this._texturePath + "/custom");
  69253. _this._animate = _this._config.animate;
  69254. _this.refreshRate = _this._config.refreshrate;
  69255. }
  69256. catch (ex) {
  69257. noConfigFile();
  69258. }
  69259. }
  69260. else {
  69261. noConfigFile();
  69262. }
  69263. }, false);
  69264. xhr.addEventListener("error", function () {
  69265. noConfigFile();
  69266. }, false);
  69267. try {
  69268. xhr.send();
  69269. }
  69270. catch (ex) {
  69271. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69272. }
  69273. };
  69274. CustomProceduralTexture.prototype.isReady = function () {
  69275. if (!_super.prototype.isReady.call(this)) {
  69276. return false;
  69277. }
  69278. for (var name in this._textures) {
  69279. var texture = this._textures[name];
  69280. if (!texture.isReady()) {
  69281. return false;
  69282. }
  69283. }
  69284. return true;
  69285. };
  69286. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69287. var scene = this.getScene();
  69288. if (this._animate && scene) {
  69289. this._time += scene.getAnimationRatio() * 0.03;
  69290. this.updateShaderUniforms();
  69291. }
  69292. _super.prototype.render.call(this, useCameraPostProcess);
  69293. };
  69294. CustomProceduralTexture.prototype.updateTextures = function () {
  69295. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69296. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69297. }
  69298. };
  69299. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69300. if (this._config) {
  69301. for (var j = 0; j < this._config.uniforms.length; j++) {
  69302. var uniform = this._config.uniforms[j];
  69303. switch (uniform.type) {
  69304. case "float":
  69305. this.setFloat(uniform.name, uniform.value);
  69306. break;
  69307. case "color3":
  69308. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69309. break;
  69310. case "color4":
  69311. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69312. break;
  69313. case "vector2":
  69314. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69315. break;
  69316. case "vector3":
  69317. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69318. break;
  69319. }
  69320. }
  69321. }
  69322. this.setFloat("time", this._time);
  69323. };
  69324. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69325. get: function () {
  69326. return this._animate;
  69327. },
  69328. set: function (value) {
  69329. this._animate = value;
  69330. },
  69331. enumerable: true,
  69332. configurable: true
  69333. });
  69334. return CustomProceduralTexture;
  69335. }(BABYLON.ProceduralTexture));
  69336. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69337. })(BABYLON || (BABYLON = {}));
  69338. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69339. var BABYLON;
  69340. (function (BABYLON) {
  69341. var FreeCameraGamepadInput = /** @class */ (function () {
  69342. function FreeCameraGamepadInput() {
  69343. this.gamepadAngularSensibility = 200;
  69344. this.gamepadMoveSensibility = 40;
  69345. // private members
  69346. this._cameraTransform = BABYLON.Matrix.Identity();
  69347. this._deltaTransform = BABYLON.Vector3.Zero();
  69348. this._vector3 = BABYLON.Vector3.Zero();
  69349. this._vector2 = BABYLON.Vector2.Zero();
  69350. }
  69351. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69352. var _this = this;
  69353. var manager = this.camera.getScene().gamepadManager;
  69354. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69355. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69356. // prioritize XBOX gamepads.
  69357. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69358. _this.gamepad = gamepad;
  69359. }
  69360. }
  69361. });
  69362. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69363. if (_this.gamepad === gamepad) {
  69364. _this.gamepad = null;
  69365. }
  69366. });
  69367. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69368. };
  69369. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69370. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69371. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69372. this.gamepad = null;
  69373. };
  69374. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69375. if (this.gamepad && this.gamepad.leftStick) {
  69376. var camera = this.camera;
  69377. var LSValues = this.gamepad.leftStick;
  69378. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69379. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69380. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69381. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69382. var RSValues = this.gamepad.rightStick;
  69383. if (RSValues) {
  69384. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69385. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69386. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69387. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69388. }
  69389. else {
  69390. RSValues = { x: 0, y: 0 };
  69391. }
  69392. if (!camera.rotationQuaternion) {
  69393. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69394. }
  69395. else {
  69396. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69397. }
  69398. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69399. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69400. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69401. camera.cameraDirection.addInPlace(this._deltaTransform);
  69402. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69403. camera.cameraRotation.addInPlace(this._vector2);
  69404. }
  69405. };
  69406. FreeCameraGamepadInput.prototype.getClassName = function () {
  69407. return "FreeCameraGamepadInput";
  69408. };
  69409. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69410. return "gamepad";
  69411. };
  69412. __decorate([
  69413. BABYLON.serialize()
  69414. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69415. __decorate([
  69416. BABYLON.serialize()
  69417. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69418. return FreeCameraGamepadInput;
  69419. }());
  69420. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69421. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69422. })(BABYLON || (BABYLON = {}));
  69423. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69424. var BABYLON;
  69425. (function (BABYLON) {
  69426. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69427. function ArcRotateCameraGamepadInput() {
  69428. this.gamepadRotationSensibility = 80;
  69429. this.gamepadMoveSensibility = 40;
  69430. }
  69431. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69432. var _this = this;
  69433. var manager = this.camera.getScene().gamepadManager;
  69434. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69435. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69436. // prioritize XBOX gamepads.
  69437. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69438. _this.gamepad = gamepad;
  69439. }
  69440. }
  69441. });
  69442. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69443. if (_this.gamepad === gamepad) {
  69444. _this.gamepad = null;
  69445. }
  69446. });
  69447. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69448. };
  69449. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69450. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69451. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69452. this.gamepad = null;
  69453. };
  69454. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69455. if (this.gamepad) {
  69456. var camera = this.camera;
  69457. var RSValues = this.gamepad.rightStick;
  69458. if (RSValues) {
  69459. if (RSValues.x != 0) {
  69460. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69461. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69462. camera.inertialAlphaOffset += normalizedRX;
  69463. }
  69464. }
  69465. if (RSValues.y != 0) {
  69466. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69467. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69468. camera.inertialBetaOffset += normalizedRY;
  69469. }
  69470. }
  69471. }
  69472. var LSValues = this.gamepad.leftStick;
  69473. if (LSValues && LSValues.y != 0) {
  69474. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69475. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69476. this.camera.inertialRadiusOffset -= normalizedLY;
  69477. }
  69478. }
  69479. }
  69480. };
  69481. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69482. return "ArcRotateCameraGamepadInput";
  69483. };
  69484. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69485. return "gamepad";
  69486. };
  69487. __decorate([
  69488. BABYLON.serialize()
  69489. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69490. __decorate([
  69491. BABYLON.serialize()
  69492. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69493. return ArcRotateCameraGamepadInput;
  69494. }());
  69495. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69496. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69497. })(BABYLON || (BABYLON = {}));
  69498. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69499. var BABYLON;
  69500. (function (BABYLON) {
  69501. var GamepadManager = /** @class */ (function () {
  69502. function GamepadManager(_scene) {
  69503. var _this = this;
  69504. this._scene = _scene;
  69505. this._babylonGamepads = [];
  69506. this._oneGamepadConnected = false;
  69507. this._isMonitoring = false;
  69508. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69509. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69510. this._gamepadEventSupported = false;
  69511. }
  69512. else {
  69513. this._gamepadEventSupported = 'GamepadEvent' in window;
  69514. this._gamepadSupport = (navigator.getGamepads ||
  69515. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69516. }
  69517. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69518. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69519. for (var i in _this._babylonGamepads) {
  69520. var gamepad = _this._babylonGamepads[i];
  69521. if (gamepad && gamepad._isConnected) {
  69522. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69523. }
  69524. }
  69525. });
  69526. this._onGamepadConnectedEvent = function (evt) {
  69527. var gamepad = evt.gamepad;
  69528. if (gamepad.index in _this._babylonGamepads) {
  69529. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69530. return;
  69531. }
  69532. }
  69533. var newGamepad;
  69534. if (_this._babylonGamepads[gamepad.index]) {
  69535. newGamepad = _this._babylonGamepads[gamepad.index];
  69536. newGamepad.browserGamepad = gamepad;
  69537. newGamepad._isConnected = true;
  69538. }
  69539. else {
  69540. newGamepad = _this._addNewGamepad(gamepad);
  69541. }
  69542. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69543. _this._startMonitoringGamepads();
  69544. };
  69545. this._onGamepadDisconnectedEvent = function (evt) {
  69546. var gamepad = evt.gamepad;
  69547. // Remove the gamepad from the list of gamepads to monitor.
  69548. for (var i in _this._babylonGamepads) {
  69549. if (_this._babylonGamepads[i].index === gamepad.index) {
  69550. var disconnectedGamepad = _this._babylonGamepads[i];
  69551. disconnectedGamepad._isConnected = false;
  69552. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69553. break;
  69554. }
  69555. }
  69556. };
  69557. if (this._gamepadSupport) {
  69558. //first add already-connected gamepads
  69559. this._updateGamepadObjects();
  69560. if (this._babylonGamepads.length) {
  69561. this._startMonitoringGamepads();
  69562. }
  69563. // Checking if the gamepad connected event is supported (like in Firefox)
  69564. if (this._gamepadEventSupported) {
  69565. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69566. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69567. }
  69568. else {
  69569. this._startMonitoringGamepads();
  69570. }
  69571. }
  69572. }
  69573. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69574. get: function () {
  69575. return this._babylonGamepads;
  69576. },
  69577. enumerable: true,
  69578. configurable: true
  69579. });
  69580. GamepadManager.prototype.getGamepadByType = function (type) {
  69581. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69582. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69583. var gamepad = _a[_i];
  69584. if (gamepad && gamepad.type === type) {
  69585. return gamepad;
  69586. }
  69587. }
  69588. return null;
  69589. };
  69590. GamepadManager.prototype.dispose = function () {
  69591. if (this._gamepadEventSupported) {
  69592. if (this._onGamepadConnectedEvent) {
  69593. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69594. }
  69595. if (this._onGamepadDisconnectedEvent) {
  69596. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69597. }
  69598. this._onGamepadConnectedEvent = null;
  69599. this._onGamepadDisconnectedEvent = null;
  69600. }
  69601. this._babylonGamepads.forEach(function (gamepad) {
  69602. gamepad.dispose();
  69603. });
  69604. this.onGamepadConnectedObservable.clear();
  69605. this.onGamepadDisconnectedObservable.clear();
  69606. this._oneGamepadConnected = false;
  69607. this._stopMonitoringGamepads();
  69608. this._babylonGamepads = [];
  69609. };
  69610. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69611. if (!this._oneGamepadConnected) {
  69612. this._oneGamepadConnected = true;
  69613. }
  69614. var newGamepad;
  69615. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69616. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69617. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69618. }
  69619. // if pose is supported, use the (WebVR) pose enabled controller
  69620. else if (gamepad.pose) {
  69621. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69622. }
  69623. else {
  69624. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69625. }
  69626. this._babylonGamepads[newGamepad.index] = newGamepad;
  69627. return newGamepad;
  69628. };
  69629. GamepadManager.prototype._startMonitoringGamepads = function () {
  69630. if (!this._isMonitoring) {
  69631. this._isMonitoring = true;
  69632. //back-comp
  69633. if (!this._scene) {
  69634. this._checkGamepadsStatus();
  69635. }
  69636. }
  69637. };
  69638. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69639. this._isMonitoring = false;
  69640. };
  69641. GamepadManager.prototype._checkGamepadsStatus = function () {
  69642. var _this = this;
  69643. // Hack to be compatible Chrome
  69644. this._updateGamepadObjects();
  69645. for (var i in this._babylonGamepads) {
  69646. var gamepad = this._babylonGamepads[i];
  69647. if (!gamepad || !gamepad.isConnected) {
  69648. continue;
  69649. }
  69650. gamepad.update();
  69651. }
  69652. if (this._isMonitoring && !this._scene) {
  69653. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69654. }
  69655. };
  69656. // This function is called only on Chrome, which does not properly support
  69657. // connection/disconnection events and forces you to recopy again the gamepad object
  69658. GamepadManager.prototype._updateGamepadObjects = function () {
  69659. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69660. for (var i = 0; i < gamepads.length; i++) {
  69661. var gamepad = gamepads[i];
  69662. if (gamepad) {
  69663. if (!this._babylonGamepads[gamepad.index]) {
  69664. var newGamepad = this._addNewGamepad(gamepad);
  69665. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69666. }
  69667. else {
  69668. // Forced to copy again this object for Chrome for unknown reason
  69669. this._babylonGamepads[i].browserGamepad = gamepad;
  69670. if (!this._babylonGamepads[i].isConnected) {
  69671. this._babylonGamepads[i]._isConnected = true;
  69672. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69673. }
  69674. }
  69675. }
  69676. }
  69677. };
  69678. return GamepadManager;
  69679. }());
  69680. BABYLON.GamepadManager = GamepadManager;
  69681. })(BABYLON || (BABYLON = {}));
  69682. //# sourceMappingURL=babylon.gamepadManager.js.map
  69683. var BABYLON;
  69684. (function (BABYLON) {
  69685. var StickValues = /** @class */ (function () {
  69686. function StickValues(x, y) {
  69687. this.x = x;
  69688. this.y = y;
  69689. }
  69690. return StickValues;
  69691. }());
  69692. BABYLON.StickValues = StickValues;
  69693. var Gamepad = /** @class */ (function () {
  69694. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69695. if (leftStickX === void 0) { leftStickX = 0; }
  69696. if (leftStickY === void 0) { leftStickY = 1; }
  69697. if (rightStickX === void 0) { rightStickX = 2; }
  69698. if (rightStickY === void 0) { rightStickY = 3; }
  69699. this.id = id;
  69700. this.index = index;
  69701. this.browserGamepad = browserGamepad;
  69702. this._isConnected = true;
  69703. this._invertLeftStickY = false;
  69704. this.type = Gamepad.GAMEPAD;
  69705. this._leftStickAxisX = leftStickX;
  69706. this._leftStickAxisY = leftStickY;
  69707. this._rightStickAxisX = rightStickX;
  69708. this._rightStickAxisY = rightStickY;
  69709. if (this.browserGamepad.axes.length >= 2) {
  69710. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69711. }
  69712. if (this.browserGamepad.axes.length >= 4) {
  69713. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69714. }
  69715. }
  69716. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69717. get: function () {
  69718. return this._isConnected;
  69719. },
  69720. enumerable: true,
  69721. configurable: true
  69722. });
  69723. Gamepad.prototype.onleftstickchanged = function (callback) {
  69724. this._onleftstickchanged = callback;
  69725. };
  69726. Gamepad.prototype.onrightstickchanged = function (callback) {
  69727. this._onrightstickchanged = callback;
  69728. };
  69729. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69730. get: function () {
  69731. return this._leftStick;
  69732. },
  69733. set: function (newValues) {
  69734. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69735. this._onleftstickchanged(newValues);
  69736. }
  69737. this._leftStick = newValues;
  69738. },
  69739. enumerable: true,
  69740. configurable: true
  69741. });
  69742. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69743. get: function () {
  69744. return this._rightStick;
  69745. },
  69746. set: function (newValues) {
  69747. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69748. this._onrightstickchanged(newValues);
  69749. }
  69750. this._rightStick = newValues;
  69751. },
  69752. enumerable: true,
  69753. configurable: true
  69754. });
  69755. Gamepad.prototype.update = function () {
  69756. if (this._leftStick) {
  69757. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69758. if (this._invertLeftStickY) {
  69759. this.leftStick.y *= -1;
  69760. }
  69761. }
  69762. if (this._rightStick) {
  69763. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69764. }
  69765. };
  69766. Gamepad.prototype.dispose = function () {
  69767. };
  69768. Gamepad.GAMEPAD = 0;
  69769. Gamepad.GENERIC = 1;
  69770. Gamepad.XBOX = 2;
  69771. Gamepad.POSE_ENABLED = 3;
  69772. return Gamepad;
  69773. }());
  69774. BABYLON.Gamepad = Gamepad;
  69775. var GenericPad = /** @class */ (function (_super) {
  69776. __extends(GenericPad, _super);
  69777. function GenericPad(id, index, browserGamepad) {
  69778. var _this = _super.call(this, id, index, browserGamepad) || this;
  69779. _this.onButtonDownObservable = new BABYLON.Observable();
  69780. _this.onButtonUpObservable = new BABYLON.Observable();
  69781. _this.type = Gamepad.GENERIC;
  69782. _this._buttons = new Array(browserGamepad.buttons.length);
  69783. return _this;
  69784. }
  69785. GenericPad.prototype.onbuttondown = function (callback) {
  69786. this._onbuttondown = callback;
  69787. };
  69788. GenericPad.prototype.onbuttonup = function (callback) {
  69789. this._onbuttonup = callback;
  69790. };
  69791. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69792. if (newValue !== currentValue) {
  69793. if (newValue === 1) {
  69794. if (this._onbuttondown) {
  69795. this._onbuttondown(buttonIndex);
  69796. }
  69797. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69798. }
  69799. if (newValue === 0) {
  69800. if (this._onbuttonup) {
  69801. this._onbuttonup(buttonIndex);
  69802. }
  69803. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69804. }
  69805. }
  69806. return newValue;
  69807. };
  69808. GenericPad.prototype.update = function () {
  69809. _super.prototype.update.call(this);
  69810. for (var index = 0; index < this._buttons.length; index++) {
  69811. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69812. }
  69813. };
  69814. GenericPad.prototype.dispose = function () {
  69815. _super.prototype.dispose.call(this);
  69816. this.onButtonDownObservable.clear();
  69817. this.onButtonUpObservable.clear();
  69818. };
  69819. return GenericPad;
  69820. }(Gamepad));
  69821. BABYLON.GenericPad = GenericPad;
  69822. })(BABYLON || (BABYLON = {}));
  69823. //# sourceMappingURL=babylon.gamepad.js.map
  69824. var BABYLON;
  69825. (function (BABYLON) {
  69826. var Xbox360Button;
  69827. (function (Xbox360Button) {
  69828. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69829. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69830. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69831. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69832. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69833. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69834. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69835. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69836. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69837. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69838. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69839. var Xbox360Dpad;
  69840. (function (Xbox360Dpad) {
  69841. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69842. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69843. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69844. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69845. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69846. var Xbox360Pad = /** @class */ (function (_super) {
  69847. __extends(Xbox360Pad, _super);
  69848. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69849. if (xboxOne === void 0) { xboxOne = false; }
  69850. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69851. _this._leftTrigger = 0;
  69852. _this._rightTrigger = 0;
  69853. _this.onButtonDownObservable = new BABYLON.Observable();
  69854. _this.onButtonUpObservable = new BABYLON.Observable();
  69855. _this.onPadDownObservable = new BABYLON.Observable();
  69856. _this.onPadUpObservable = new BABYLON.Observable();
  69857. _this._buttonA = 0;
  69858. _this._buttonB = 0;
  69859. _this._buttonX = 0;
  69860. _this._buttonY = 0;
  69861. _this._buttonBack = 0;
  69862. _this._buttonStart = 0;
  69863. _this._buttonLB = 0;
  69864. _this._buttonRB = 0;
  69865. _this._buttonLeftStick = 0;
  69866. _this._buttonRightStick = 0;
  69867. _this._dPadUp = 0;
  69868. _this._dPadDown = 0;
  69869. _this._dPadLeft = 0;
  69870. _this._dPadRight = 0;
  69871. _this._isXboxOnePad = false;
  69872. _this.type = BABYLON.Gamepad.XBOX;
  69873. _this._isXboxOnePad = xboxOne;
  69874. return _this;
  69875. }
  69876. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69877. this._onlefttriggerchanged = callback;
  69878. };
  69879. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69880. this._onrighttriggerchanged = callback;
  69881. };
  69882. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69883. get: function () {
  69884. return this._leftTrigger;
  69885. },
  69886. set: function (newValue) {
  69887. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69888. this._onlefttriggerchanged(newValue);
  69889. }
  69890. this._leftTrigger = newValue;
  69891. },
  69892. enumerable: true,
  69893. configurable: true
  69894. });
  69895. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69896. get: function () {
  69897. return this._rightTrigger;
  69898. },
  69899. set: function (newValue) {
  69900. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  69901. this._onrighttriggerchanged(newValue);
  69902. }
  69903. this._rightTrigger = newValue;
  69904. },
  69905. enumerable: true,
  69906. configurable: true
  69907. });
  69908. Xbox360Pad.prototype.onbuttondown = function (callback) {
  69909. this._onbuttondown = callback;
  69910. };
  69911. Xbox360Pad.prototype.onbuttonup = function (callback) {
  69912. this._onbuttonup = callback;
  69913. };
  69914. Xbox360Pad.prototype.ondpaddown = function (callback) {
  69915. this._ondpaddown = callback;
  69916. };
  69917. Xbox360Pad.prototype.ondpadup = function (callback) {
  69918. this._ondpadup = callback;
  69919. };
  69920. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  69921. if (newValue !== currentValue) {
  69922. if (newValue === 1) {
  69923. if (this._onbuttondown) {
  69924. this._onbuttondown(buttonType);
  69925. }
  69926. this.onButtonDownObservable.notifyObservers(buttonType);
  69927. }
  69928. if (newValue === 0) {
  69929. if (this._onbuttonup) {
  69930. this._onbuttonup(buttonType);
  69931. }
  69932. this.onButtonUpObservable.notifyObservers(buttonType);
  69933. }
  69934. }
  69935. return newValue;
  69936. };
  69937. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  69938. if (newValue !== currentValue) {
  69939. if (newValue === 1) {
  69940. if (this._ondpaddown) {
  69941. this._ondpaddown(buttonType);
  69942. }
  69943. this.onPadDownObservable.notifyObservers(buttonType);
  69944. }
  69945. if (newValue === 0) {
  69946. if (this._ondpadup) {
  69947. this._ondpadup(buttonType);
  69948. }
  69949. this.onPadUpObservable.notifyObservers(buttonType);
  69950. }
  69951. }
  69952. return newValue;
  69953. };
  69954. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  69955. get: function () {
  69956. return this._buttonA;
  69957. },
  69958. set: function (value) {
  69959. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  69960. },
  69961. enumerable: true,
  69962. configurable: true
  69963. });
  69964. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  69965. get: function () {
  69966. return this._buttonB;
  69967. },
  69968. set: function (value) {
  69969. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  69970. },
  69971. enumerable: true,
  69972. configurable: true
  69973. });
  69974. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  69975. get: function () {
  69976. return this._buttonX;
  69977. },
  69978. set: function (value) {
  69979. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  69980. },
  69981. enumerable: true,
  69982. configurable: true
  69983. });
  69984. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  69985. get: function () {
  69986. return this._buttonY;
  69987. },
  69988. set: function (value) {
  69989. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  69990. },
  69991. enumerable: true,
  69992. configurable: true
  69993. });
  69994. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  69995. get: function () {
  69996. return this._buttonStart;
  69997. },
  69998. set: function (value) {
  69999. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70000. },
  70001. enumerable: true,
  70002. configurable: true
  70003. });
  70004. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70005. get: function () {
  70006. return this._buttonBack;
  70007. },
  70008. set: function (value) {
  70009. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70010. },
  70011. enumerable: true,
  70012. configurable: true
  70013. });
  70014. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70015. get: function () {
  70016. return this._buttonLB;
  70017. },
  70018. set: function (value) {
  70019. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70020. },
  70021. enumerable: true,
  70022. configurable: true
  70023. });
  70024. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70025. get: function () {
  70026. return this._buttonRB;
  70027. },
  70028. set: function (value) {
  70029. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70030. },
  70031. enumerable: true,
  70032. configurable: true
  70033. });
  70034. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70035. get: function () {
  70036. return this._buttonLeftStick;
  70037. },
  70038. set: function (value) {
  70039. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70040. },
  70041. enumerable: true,
  70042. configurable: true
  70043. });
  70044. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70045. get: function () {
  70046. return this._buttonRightStick;
  70047. },
  70048. set: function (value) {
  70049. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70050. },
  70051. enumerable: true,
  70052. configurable: true
  70053. });
  70054. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70055. get: function () {
  70056. return this._dPadUp;
  70057. },
  70058. set: function (value) {
  70059. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70060. },
  70061. enumerable: true,
  70062. configurable: true
  70063. });
  70064. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70065. get: function () {
  70066. return this._dPadDown;
  70067. },
  70068. set: function (value) {
  70069. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70070. },
  70071. enumerable: true,
  70072. configurable: true
  70073. });
  70074. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70075. get: function () {
  70076. return this._dPadLeft;
  70077. },
  70078. set: function (value) {
  70079. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70080. },
  70081. enumerable: true,
  70082. configurable: true
  70083. });
  70084. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70085. get: function () {
  70086. return this._dPadRight;
  70087. },
  70088. set: function (value) {
  70089. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70090. },
  70091. enumerable: true,
  70092. configurable: true
  70093. });
  70094. Xbox360Pad.prototype.update = function () {
  70095. _super.prototype.update.call(this);
  70096. if (this._isXboxOnePad) {
  70097. this.buttonA = this.browserGamepad.buttons[0].value;
  70098. this.buttonB = this.browserGamepad.buttons[1].value;
  70099. this.buttonX = this.browserGamepad.buttons[2].value;
  70100. this.buttonY = this.browserGamepad.buttons[3].value;
  70101. this.buttonLB = this.browserGamepad.buttons[4].value;
  70102. this.buttonRB = this.browserGamepad.buttons[5].value;
  70103. this.leftTrigger = this.browserGamepad.axes[2];
  70104. this.rightTrigger = this.browserGamepad.axes[5];
  70105. this.buttonBack = this.browserGamepad.buttons[9].value;
  70106. this.buttonStart = this.browserGamepad.buttons[8].value;
  70107. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70108. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70109. this.dPadUp = this.browserGamepad.buttons[11].value;
  70110. this.dPadDown = this.browserGamepad.buttons[12].value;
  70111. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70112. this.dPadRight = this.browserGamepad.buttons[14].value;
  70113. }
  70114. else {
  70115. this.buttonA = this.browserGamepad.buttons[0].value;
  70116. this.buttonB = this.browserGamepad.buttons[1].value;
  70117. this.buttonX = this.browserGamepad.buttons[2].value;
  70118. this.buttonY = this.browserGamepad.buttons[3].value;
  70119. this.buttonLB = this.browserGamepad.buttons[4].value;
  70120. this.buttonRB = this.browserGamepad.buttons[5].value;
  70121. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70122. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70123. this.buttonBack = this.browserGamepad.buttons[8].value;
  70124. this.buttonStart = this.browserGamepad.buttons[9].value;
  70125. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70126. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70127. this.dPadUp = this.browserGamepad.buttons[12].value;
  70128. this.dPadDown = this.browserGamepad.buttons[13].value;
  70129. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70130. this.dPadRight = this.browserGamepad.buttons[15].value;
  70131. }
  70132. };
  70133. Xbox360Pad.prototype.dispose = function () {
  70134. _super.prototype.dispose.call(this);
  70135. this.onButtonDownObservable.clear();
  70136. this.onButtonUpObservable.clear();
  70137. this.onPadDownObservable.clear();
  70138. this.onPadUpObservable.clear();
  70139. };
  70140. return Xbox360Pad;
  70141. }(BABYLON.Gamepad));
  70142. BABYLON.Xbox360Pad = Xbox360Pad;
  70143. })(BABYLON || (BABYLON = {}));
  70144. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70145. var BABYLON;
  70146. (function (BABYLON) {
  70147. /**
  70148. * Defines the types of pose enabled controllers that are supported
  70149. */
  70150. var PoseEnabledControllerType;
  70151. (function (PoseEnabledControllerType) {
  70152. /**
  70153. * HTC Vive
  70154. */
  70155. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70156. /**
  70157. * Oculus Rift
  70158. */
  70159. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70160. /**
  70161. * Windows mixed reality
  70162. */
  70163. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70164. /**
  70165. * Samsung gear VR
  70166. */
  70167. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70168. /**
  70169. * Google Daydream
  70170. */
  70171. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70172. /**
  70173. * Generic
  70174. */
  70175. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70176. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70177. /**
  70178. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70179. */
  70180. var PoseEnabledControllerHelper = /** @class */ (function () {
  70181. function PoseEnabledControllerHelper() {
  70182. }
  70183. /**
  70184. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70185. * @param vrGamepad the gamepad to initialized
  70186. * @returns a vr controller of the type the gamepad identified as
  70187. */
  70188. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70189. // Oculus Touch
  70190. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70191. return new BABYLON.OculusTouchController(vrGamepad);
  70192. }
  70193. // Windows Mixed Reality controllers
  70194. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70195. return new BABYLON.WindowsMotionController(vrGamepad);
  70196. }
  70197. // HTC Vive
  70198. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70199. return new BABYLON.ViveController(vrGamepad);
  70200. }
  70201. // Samsung/Oculus Gear VR
  70202. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70203. return new BABYLON.GearVRController(vrGamepad);
  70204. }
  70205. // Google Daydream
  70206. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70207. return new BABYLON.DaydreamController(vrGamepad);
  70208. }
  70209. // Generic
  70210. else {
  70211. return new BABYLON.GenericController(vrGamepad);
  70212. }
  70213. };
  70214. return PoseEnabledControllerHelper;
  70215. }());
  70216. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70217. /**
  70218. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70219. */
  70220. var PoseEnabledController = /** @class */ (function (_super) {
  70221. __extends(PoseEnabledController, _super);
  70222. /**
  70223. * Creates a new PoseEnabledController from a gamepad
  70224. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70225. */
  70226. function PoseEnabledController(browserGamepad) {
  70227. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70228. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70229. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70230. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70231. /**
  70232. * The device position in babylon space
  70233. */
  70234. _this.devicePosition = BABYLON.Vector3.Zero();
  70235. /**
  70236. * The device rotation in babylon space
  70237. */
  70238. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70239. /**
  70240. * The scale factor of the device in babylon space
  70241. */
  70242. _this.deviceScaleFactor = 1;
  70243. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70244. /**
  70245. * Internal, matrix used to convert room space to babylon space
  70246. */
  70247. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70248. /**
  70249. * Node to be used when casting a ray from the controller
  70250. */
  70251. _this._pointingPoseNode = null;
  70252. _this._workingMatrix = BABYLON.Matrix.Identity();
  70253. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70254. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70255. _this.position = BABYLON.Vector3.Zero();
  70256. _this.rotationQuaternion = new BABYLON.Quaternion();
  70257. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70258. _this._calculatedRotation = new BABYLON.Quaternion();
  70259. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70260. return _this;
  70261. }
  70262. /**
  70263. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70264. */
  70265. PoseEnabledController.prototype.update = function () {
  70266. _super.prototype.update.call(this);
  70267. var pose = this.browserGamepad.pose;
  70268. this.updateFromDevice(pose);
  70269. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70270. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70271. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70272. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70273. if (this._mesh) {
  70274. this._mesh.position.copyFrom(this.devicePosition);
  70275. if (this._mesh.rotationQuaternion) {
  70276. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70277. }
  70278. }
  70279. };
  70280. /**
  70281. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70282. * @param poseData raw pose fromthe device
  70283. */
  70284. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70285. if (poseData) {
  70286. this.rawPose = poseData;
  70287. if (poseData.position) {
  70288. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70289. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70290. this._deviceRoomPosition.z *= -1;
  70291. }
  70292. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70293. this._calculatedPosition.addInPlace(this.position);
  70294. }
  70295. var pose = this.rawPose;
  70296. if (poseData.orientation && pose.orientation) {
  70297. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70298. if (this._mesh) {
  70299. if (this._mesh.getScene().useRightHandedSystem) {
  70300. this._deviceRoomRotationQuaternion.z *= -1;
  70301. this._deviceRoomRotationQuaternion.w *= -1;
  70302. }
  70303. else {
  70304. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70305. }
  70306. }
  70307. // if the camera is set, rotate to the camera's rotation
  70308. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70309. }
  70310. }
  70311. };
  70312. /**
  70313. * Attaches a mesh to the controller
  70314. * @param mesh the mesh to be attached
  70315. */
  70316. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70317. if (this._mesh) {
  70318. this._mesh.parent = null;
  70319. }
  70320. this._mesh = mesh;
  70321. if (this._poseControlledCamera) {
  70322. this._mesh.parent = this._poseControlledCamera;
  70323. }
  70324. if (!this._mesh.rotationQuaternion) {
  70325. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70326. }
  70327. };
  70328. /**
  70329. * Attaches the controllers mesh to a camera
  70330. * @param camera the camera the mesh should be attached to
  70331. */
  70332. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70333. this._poseControlledCamera = camera;
  70334. if (this._mesh) {
  70335. this._mesh.parent = this._poseControlledCamera;
  70336. }
  70337. };
  70338. /**
  70339. * Disposes of the controller
  70340. */
  70341. PoseEnabledController.prototype.dispose = function () {
  70342. if (this._mesh) {
  70343. this._mesh.dispose();
  70344. }
  70345. this._mesh = null;
  70346. _super.prototype.dispose.call(this);
  70347. };
  70348. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70349. /**
  70350. * The mesh that is attached to the controller
  70351. */
  70352. get: function () {
  70353. return this._mesh;
  70354. },
  70355. enumerable: true,
  70356. configurable: true
  70357. });
  70358. /**
  70359. * Gets the ray of the controller in the direction the controller is pointing
  70360. * @param length the length the resulting ray should be
  70361. * @returns a ray in the direction the controller is pointing
  70362. */
  70363. PoseEnabledController.prototype.getForwardRay = function (length) {
  70364. if (length === void 0) { length = 100; }
  70365. if (!this.mesh) {
  70366. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70367. }
  70368. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70369. var origin = m.getTranslation();
  70370. var forward = new BABYLON.Vector3(0, 0, -1);
  70371. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70372. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70373. return new BABYLON.Ray(origin, direction, length);
  70374. };
  70375. /**
  70376. * Name of the child mesh that can be used to cast a ray from the controller
  70377. */
  70378. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70379. return PoseEnabledController;
  70380. }(BABYLON.Gamepad));
  70381. BABYLON.PoseEnabledController = PoseEnabledController;
  70382. })(BABYLON || (BABYLON = {}));
  70383. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70384. var BABYLON;
  70385. (function (BABYLON) {
  70386. /**
  70387. * Defines the WebVRController object that represents controllers tracked in 3D space
  70388. */
  70389. var WebVRController = /** @class */ (function (_super) {
  70390. __extends(WebVRController, _super);
  70391. /**
  70392. * Creates a new WebVRController from a gamepad
  70393. * @param vrGamepad the gamepad that the WebVRController should be created from
  70394. */
  70395. function WebVRController(vrGamepad) {
  70396. var _this = _super.call(this, vrGamepad) || this;
  70397. // Observables
  70398. /**
  70399. * Fired when the trigger state has changed
  70400. */
  70401. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70402. /**
  70403. * Fired when the main button state has changed
  70404. */
  70405. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70406. /**
  70407. * Fired when the secondary button state has changed
  70408. */
  70409. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70410. /**
  70411. * Fired when the pad state has changed
  70412. */
  70413. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70414. /**
  70415. * Fired when controllers stick values have changed
  70416. */
  70417. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70418. /**
  70419. * X and Y axis corrisponding to the controllers joystick
  70420. */
  70421. _this.pad = { x: 0, y: 0 };
  70422. // avoid GC, store state in a tmp object
  70423. _this._changes = {
  70424. pressChanged: false,
  70425. touchChanged: false,
  70426. valueChanged: false,
  70427. changed: false
  70428. };
  70429. _this._buttons = new Array(vrGamepad.buttons.length);
  70430. _this.hand = vrGamepad.hand;
  70431. return _this;
  70432. }
  70433. /**
  70434. * Fired when a controller button's state has changed
  70435. * @param callback the callback containing the button that was modified
  70436. */
  70437. WebVRController.prototype.onButtonStateChange = function (callback) {
  70438. this._onButtonStateChange = callback;
  70439. };
  70440. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70441. /**
  70442. * The default controller model for the controller
  70443. */
  70444. get: function () {
  70445. return this._defaultModel;
  70446. },
  70447. enumerable: true,
  70448. configurable: true
  70449. });
  70450. /**
  70451. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70452. */
  70453. WebVRController.prototype.update = function () {
  70454. _super.prototype.update.call(this);
  70455. for (var index = 0; index < this._buttons.length; index++) {
  70456. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70457. }
  70458. ;
  70459. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70460. this.pad.x = this.leftStick.x;
  70461. this.pad.y = this.leftStick.y;
  70462. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70463. }
  70464. };
  70465. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70466. if (!newState) {
  70467. newState = {
  70468. pressed: false,
  70469. touched: false,
  70470. value: 0
  70471. };
  70472. }
  70473. if (!currentState) {
  70474. this._buttons[buttonIndex] = {
  70475. pressed: newState.pressed,
  70476. touched: newState.touched,
  70477. value: newState.value
  70478. };
  70479. return;
  70480. }
  70481. this._checkChanges(newState, currentState);
  70482. if (this._changes.changed) {
  70483. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70484. this._handleButtonChange(buttonIndex, newState, this._changes);
  70485. }
  70486. this._buttons[buttonIndex].pressed = newState.pressed;
  70487. this._buttons[buttonIndex].touched = newState.touched;
  70488. // oculus triggers are never 0, thou not touched.
  70489. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70490. };
  70491. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70492. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70493. this._changes.touchChanged = newState.touched !== currentState.touched;
  70494. this._changes.valueChanged = newState.value !== currentState.value;
  70495. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70496. return this._changes;
  70497. };
  70498. /**
  70499. * Disposes of th webVRCOntroller
  70500. */
  70501. WebVRController.prototype.dispose = function () {
  70502. _super.prototype.dispose.call(this);
  70503. this.onTriggerStateChangedObservable.clear();
  70504. this.onMainButtonStateChangedObservable.clear();
  70505. this.onSecondaryButtonStateChangedObservable.clear();
  70506. this.onPadStateChangedObservable.clear();
  70507. this.onPadValuesChangedObservable.clear();
  70508. };
  70509. return WebVRController;
  70510. }(BABYLON.PoseEnabledController));
  70511. BABYLON.WebVRController = WebVRController;
  70512. })(BABYLON || (BABYLON = {}));
  70513. //# sourceMappingURL=babylon.webVRController.js.map
  70514. var BABYLON;
  70515. (function (BABYLON) {
  70516. /**
  70517. * Oculus Touch Controller
  70518. */
  70519. var OculusTouchController = /** @class */ (function (_super) {
  70520. __extends(OculusTouchController, _super);
  70521. /**
  70522. * Creates a new OculusTouchController from a gamepad
  70523. * @param vrGamepad the gamepad that the controller should be created from
  70524. */
  70525. function OculusTouchController(vrGamepad) {
  70526. var _this = _super.call(this, vrGamepad) || this;
  70527. /**
  70528. * Fired when the secondary trigger on this controller is modified
  70529. */
  70530. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70531. /**
  70532. * Fired when the thumb rest on this controller is modified
  70533. */
  70534. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70535. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70536. return _this;
  70537. }
  70538. /**
  70539. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70540. * @param scene scene in which to add meshes
  70541. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70542. */
  70543. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70544. var _this = this;
  70545. var meshName;
  70546. // Hand
  70547. if (this.hand === 'left') {
  70548. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70549. }
  70550. else { // Right is the default if no hand is specified
  70551. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70552. }
  70553. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70554. /*
  70555. Parent Mesh name: oculus_touch_left
  70556. - body
  70557. - trigger
  70558. - thumbstick
  70559. - grip
  70560. - button_y
  70561. - button_x
  70562. - button_enter
  70563. */
  70564. _this._defaultModel = newMeshes[1];
  70565. _this.attachToMesh(_this._defaultModel);
  70566. if (meshLoaded) {
  70567. meshLoaded(_this._defaultModel);
  70568. }
  70569. });
  70570. };
  70571. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70572. /**
  70573. * Fired when the A button on this controller is modified
  70574. */
  70575. get: function () {
  70576. if (this.hand === 'right') {
  70577. return this.onMainButtonStateChangedObservable;
  70578. }
  70579. else {
  70580. throw new Error('No A button on left hand');
  70581. }
  70582. },
  70583. enumerable: true,
  70584. configurable: true
  70585. });
  70586. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70587. /**
  70588. * Fired when the B button on this controller is modified
  70589. */
  70590. get: function () {
  70591. if (this.hand === 'right') {
  70592. return this.onSecondaryButtonStateChangedObservable;
  70593. }
  70594. else {
  70595. throw new Error('No B button on left hand');
  70596. }
  70597. },
  70598. enumerable: true,
  70599. configurable: true
  70600. });
  70601. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70602. /**
  70603. * Fired when the X button on this controller is modified
  70604. */
  70605. get: function () {
  70606. if (this.hand === 'left') {
  70607. return this.onMainButtonStateChangedObservable;
  70608. }
  70609. else {
  70610. throw new Error('No X button on right hand');
  70611. }
  70612. },
  70613. enumerable: true,
  70614. configurable: true
  70615. });
  70616. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70617. /**
  70618. * Fired when the Y button on this controller is modified
  70619. */
  70620. get: function () {
  70621. if (this.hand === 'left') {
  70622. return this.onSecondaryButtonStateChangedObservable;
  70623. }
  70624. else {
  70625. throw new Error('No Y button on right hand');
  70626. }
  70627. },
  70628. enumerable: true,
  70629. configurable: true
  70630. });
  70631. /**
  70632. * Called once for each button that changed state since the last frame
  70633. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70634. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70635. * 2) secondary trigger (same)
  70636. * 3) A (right) X (left), touch, pressed = value
  70637. * 4) B / Y
  70638. * 5) thumb rest
  70639. * @param buttonIdx Which button index changed
  70640. * @param state New state of the button
  70641. * @param changes Which properties on the state changed since last frame
  70642. */
  70643. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70644. var notifyObject = state; //{ state: state, changes: changes };
  70645. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70646. switch (buttonIdx) {
  70647. case 0:
  70648. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70649. return;
  70650. case 1: // index trigger
  70651. if (this._defaultModel) {
  70652. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70653. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70654. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70655. }
  70656. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70657. return;
  70658. case 2: // secondary trigger
  70659. if (this._defaultModel) {
  70660. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70661. }
  70662. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70663. return;
  70664. case 3:
  70665. if (this._defaultModel) {
  70666. if (notifyObject.pressed) {
  70667. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70668. }
  70669. else {
  70670. (this._defaultModel.getChildren()[1]).position.y = 0;
  70671. }
  70672. }
  70673. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70674. return;
  70675. case 4:
  70676. if (this._defaultModel) {
  70677. if (notifyObject.pressed) {
  70678. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70679. }
  70680. else {
  70681. (this._defaultModel.getChildren()[2]).position.y = 0;
  70682. }
  70683. }
  70684. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70685. return;
  70686. case 5:
  70687. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70688. return;
  70689. }
  70690. };
  70691. /**
  70692. * Base Url for the controller model.
  70693. */
  70694. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70695. /**
  70696. * File name for the left controller model.
  70697. */
  70698. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70699. /**
  70700. * File name for the right controller model.
  70701. */
  70702. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70703. return OculusTouchController;
  70704. }(BABYLON.WebVRController));
  70705. BABYLON.OculusTouchController = OculusTouchController;
  70706. })(BABYLON || (BABYLON = {}));
  70707. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70708. var BABYLON;
  70709. (function (BABYLON) {
  70710. /**
  70711. * Vive Controller
  70712. */
  70713. var ViveController = /** @class */ (function (_super) {
  70714. __extends(ViveController, _super);
  70715. /**
  70716. * Creates a new ViveController from a gamepad
  70717. * @param vrGamepad the gamepad that the controller should be created from
  70718. */
  70719. function ViveController(vrGamepad) {
  70720. var _this = _super.call(this, vrGamepad) || this;
  70721. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70722. _this._invertLeftStickY = true;
  70723. return _this;
  70724. }
  70725. /**
  70726. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70727. * @param scene scene in which to add meshes
  70728. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70729. */
  70730. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70731. var _this = this;
  70732. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70733. /*
  70734. Parent Mesh name: ViveWand
  70735. - body
  70736. - r_gripper
  70737. - l_gripper
  70738. - menu_button
  70739. - system_button
  70740. - trackpad
  70741. - trigger
  70742. - LED
  70743. */
  70744. _this._defaultModel = newMeshes[1];
  70745. _this.attachToMesh(_this._defaultModel);
  70746. if (meshLoaded) {
  70747. meshLoaded(_this._defaultModel);
  70748. }
  70749. });
  70750. };
  70751. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70752. /**
  70753. * Fired when the left button on this controller is modified
  70754. */
  70755. get: function () {
  70756. return this.onMainButtonStateChangedObservable;
  70757. },
  70758. enumerable: true,
  70759. configurable: true
  70760. });
  70761. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70762. /**
  70763. * Fired when the right button on this controller is modified
  70764. */
  70765. get: function () {
  70766. return this.onMainButtonStateChangedObservable;
  70767. },
  70768. enumerable: true,
  70769. configurable: true
  70770. });
  70771. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70772. /**
  70773. * Fired when the menu button on this controller is modified
  70774. */
  70775. get: function () {
  70776. return this.onSecondaryButtonStateChangedObservable;
  70777. },
  70778. enumerable: true,
  70779. configurable: true
  70780. });
  70781. /**
  70782. * Called once for each button that changed state since the last frame
  70783. * Vive mapping:
  70784. * 0: touchpad
  70785. * 1: trigger
  70786. * 2: left AND right buttons
  70787. * 3: menu button
  70788. * @param buttonIdx Which button index changed
  70789. * @param state New state of the button
  70790. * @param changes Which properties on the state changed since last frame
  70791. */
  70792. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70793. var notifyObject = state; //{ state: state, changes: changes };
  70794. switch (buttonIdx) {
  70795. case 0:
  70796. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70797. return;
  70798. case 1: // index trigger
  70799. if (this._defaultModel) {
  70800. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70801. }
  70802. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70803. return;
  70804. case 2: // left AND right button
  70805. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70806. return;
  70807. case 3:
  70808. if (this._defaultModel) {
  70809. if (notifyObject.pressed) {
  70810. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70811. }
  70812. else {
  70813. (this._defaultModel.getChildren()[2]).position.y = 0;
  70814. }
  70815. }
  70816. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70817. return;
  70818. }
  70819. };
  70820. /**
  70821. * Base Url for the controller model.
  70822. */
  70823. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70824. /**
  70825. * File name for the controller model.
  70826. */
  70827. ViveController.MODEL_FILENAME = 'wand.babylon';
  70828. return ViveController;
  70829. }(BABYLON.WebVRController));
  70830. BABYLON.ViveController = ViveController;
  70831. })(BABYLON || (BABYLON = {}));
  70832. //# sourceMappingURL=babylon.viveController.js.map
  70833. var BABYLON;
  70834. (function (BABYLON) {
  70835. /**
  70836. * Generic Controller
  70837. */
  70838. var GenericController = /** @class */ (function (_super) {
  70839. __extends(GenericController, _super);
  70840. /**
  70841. * Creates a new GenericController from a gamepad
  70842. * @param vrGamepad the gamepad that the controller should be created from
  70843. */
  70844. function GenericController(vrGamepad) {
  70845. return _super.call(this, vrGamepad) || this;
  70846. }
  70847. /**
  70848. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70849. * @param scene scene in which to add meshes
  70850. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70851. */
  70852. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70853. var _this = this;
  70854. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70855. _this._defaultModel = newMeshes[1];
  70856. _this.attachToMesh(_this._defaultModel);
  70857. if (meshLoaded) {
  70858. meshLoaded(_this._defaultModel);
  70859. }
  70860. });
  70861. };
  70862. /**
  70863. * Called once for each button that changed state since the last frame
  70864. * @param buttonIdx Which button index changed
  70865. * @param state New state of the button
  70866. * @param changes Which properties on the state changed since last frame
  70867. */
  70868. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70869. console.log("Button id: " + buttonIdx + "state: ");
  70870. console.dir(state);
  70871. };
  70872. /**
  70873. * Base Url for the controller model.
  70874. */
  70875. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  70876. /**
  70877. * File name for the controller model.
  70878. */
  70879. GenericController.MODEL_FILENAME = 'generic.babylon';
  70880. return GenericController;
  70881. }(BABYLON.WebVRController));
  70882. BABYLON.GenericController = GenericController;
  70883. })(BABYLON || (BABYLON = {}));
  70884. //# sourceMappingURL=babylon.genericController.js.map
  70885. var BABYLON;
  70886. (function (BABYLON) {
  70887. /**
  70888. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  70889. */
  70890. var LoadedMeshInfo = /** @class */ (function () {
  70891. function LoadedMeshInfo() {
  70892. /**
  70893. * Map of the button meshes contained in the controller
  70894. */
  70895. this.buttonMeshes = {};
  70896. /**
  70897. * Map of the axis meshes contained in the controller
  70898. */
  70899. this.axisMeshes = {};
  70900. }
  70901. return LoadedMeshInfo;
  70902. }());
  70903. /**
  70904. * Defines the WindowsMotionController object that the state of the windows motion controller
  70905. */
  70906. var WindowsMotionController = /** @class */ (function (_super) {
  70907. __extends(WindowsMotionController, _super);
  70908. /**
  70909. * Creates a new WindowsMotionController from a gamepad
  70910. * @param vrGamepad the gamepad that the controller should be created from
  70911. */
  70912. function WindowsMotionController(vrGamepad) {
  70913. var _this = _super.call(this, vrGamepad) || this;
  70914. _this._mapping = {
  70915. // Semantic button names
  70916. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  70917. // A mapping of the button name to glTF model node name
  70918. // that should be transformed by button value.
  70919. buttonMeshNames: {
  70920. 'trigger': 'SELECT',
  70921. 'menu': 'MENU',
  70922. 'grip': 'GRASP',
  70923. 'thumbstick': 'THUMBSTICK_PRESS',
  70924. 'trackpad': 'TOUCHPAD_PRESS'
  70925. },
  70926. // This mapping is used to translate from the Motion Controller to Babylon semantics
  70927. buttonObservableNames: {
  70928. 'trigger': 'onTriggerStateChangedObservable',
  70929. 'menu': 'onSecondaryButtonStateChangedObservable',
  70930. 'grip': 'onMainButtonStateChangedObservable',
  70931. 'thumbstick': 'onPadStateChangedObservable',
  70932. 'trackpad': 'onTrackpadChangedObservable'
  70933. },
  70934. // A mapping of the axis name to glTF model node name
  70935. // that should be transformed by axis value.
  70936. // This array mirrors the browserGamepad.axes array, such that
  70937. // the mesh corresponding to axis 0 is in this array index 0.
  70938. axisMeshNames: [
  70939. 'THUMBSTICK_X',
  70940. 'THUMBSTICK_Y',
  70941. 'TOUCHPAD_TOUCH_X',
  70942. 'TOUCHPAD_TOUCH_Y'
  70943. ],
  70944. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  70945. };
  70946. /**
  70947. * Fired when the trackpad on this controller is clicked
  70948. */
  70949. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  70950. /**
  70951. * Fired when the trackpad on this controller is modified
  70952. */
  70953. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  70954. /**
  70955. * The current x and y values of this controller's trackpad
  70956. */
  70957. _this.trackpad = { x: 0, y: 0 };
  70958. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  70959. _this._loadedMeshInfo = null;
  70960. return _this;
  70961. }
  70962. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  70963. /**
  70964. * Fired when the trigger on this controller is modified
  70965. */
  70966. get: function () {
  70967. return this.onTriggerStateChangedObservable;
  70968. },
  70969. enumerable: true,
  70970. configurable: true
  70971. });
  70972. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  70973. /**
  70974. * Fired when the menu button on this controller is modified
  70975. */
  70976. get: function () {
  70977. return this.onSecondaryButtonStateChangedObservable;
  70978. },
  70979. enumerable: true,
  70980. configurable: true
  70981. });
  70982. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  70983. /**
  70984. * Fired when the grip button on this controller is modified
  70985. */
  70986. get: function () {
  70987. return this.onMainButtonStateChangedObservable;
  70988. },
  70989. enumerable: true,
  70990. configurable: true
  70991. });
  70992. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  70993. /**
  70994. * Fired when the thumbstick button on this controller is modified
  70995. */
  70996. get: function () {
  70997. return this.onPadStateChangedObservable;
  70998. },
  70999. enumerable: true,
  71000. configurable: true
  71001. });
  71002. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71003. /**
  71004. * Fired when the touchpad button on this controller is modified
  71005. */
  71006. get: function () {
  71007. return this.onTrackpadChangedObservable;
  71008. },
  71009. enumerable: true,
  71010. configurable: true
  71011. });
  71012. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71013. /**
  71014. * Fired when the touchpad values on this controller are modified
  71015. */
  71016. get: function () {
  71017. return this.onTrackpadValuesChangedObservable;
  71018. },
  71019. enumerable: true,
  71020. configurable: true
  71021. });
  71022. /**
  71023. * Called once per frame by the engine.
  71024. */
  71025. WindowsMotionController.prototype.update = function () {
  71026. _super.prototype.update.call(this);
  71027. if (this.browserGamepad.axes) {
  71028. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71029. this.trackpad.x = this.browserGamepad["axes"][2];
  71030. this.trackpad.y = this.browserGamepad["axes"][3];
  71031. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71032. }
  71033. // Only need to animate axes if there is a loaded mesh
  71034. if (this._loadedMeshInfo) {
  71035. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71036. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71037. }
  71038. }
  71039. }
  71040. };
  71041. /**
  71042. * Called once for each button that changed state since the last frame
  71043. * @param buttonIdx Which button index changed
  71044. * @param state New state of the button
  71045. * @param changes Which properties on the state changed since last frame
  71046. */
  71047. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71048. var buttonName = this._mapping.buttons[buttonIdx];
  71049. if (!buttonName) {
  71050. return;
  71051. }
  71052. // Only emit events for buttons that we know how to map from index to name
  71053. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71054. if (observable) {
  71055. observable.notifyObservers(state);
  71056. }
  71057. this._lerpButtonTransform(buttonName, state.value);
  71058. };
  71059. /**
  71060. * Moves the buttons on the controller mesh based on their current state
  71061. * @param buttonName the name of the button to move
  71062. * @param buttonValue the value of the button which determines the buttons new position
  71063. */
  71064. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71065. // If there is no loaded mesh, there is nothing to transform.
  71066. if (!this._loadedMeshInfo) {
  71067. return;
  71068. }
  71069. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71070. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71071. return;
  71072. }
  71073. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71074. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71075. };
  71076. /**
  71077. * Moves the axis on the controller mesh based on its current state
  71078. * @param axis the index of the axis
  71079. * @param axisValue the value of the axis which determines the meshes new position
  71080. * @ignore
  71081. */
  71082. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71083. if (!this._loadedMeshInfo) {
  71084. return;
  71085. }
  71086. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71087. if (!meshInfo) {
  71088. return;
  71089. }
  71090. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71091. return;
  71092. }
  71093. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71094. var lerpValue = axisValue * 0.5 + 0.5;
  71095. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71096. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71097. };
  71098. /**
  71099. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71100. * @param scene scene in which to add meshes
  71101. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71102. */
  71103. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71104. var _this = this;
  71105. if (forceDefault === void 0) { forceDefault = false; }
  71106. var path;
  71107. var filename;
  71108. // Checking if GLB loader is present
  71109. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71110. // Determine the device specific folder based on the ID suffix
  71111. var device = 'default';
  71112. if (this.id && !forceDefault) {
  71113. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71114. device = ((match && match[0]) || device);
  71115. }
  71116. // Hand
  71117. if (this.hand === 'left') {
  71118. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71119. }
  71120. else { // Right is the default if no hand is specified
  71121. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71122. }
  71123. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71124. }
  71125. else {
  71126. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71127. path = BABYLON.GenericController.MODEL_BASE_URL;
  71128. filename = BABYLON.GenericController.MODEL_FILENAME;
  71129. }
  71130. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71131. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71132. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71133. if (!_this._loadedMeshInfo) {
  71134. return;
  71135. }
  71136. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71137. _this.attachToMesh(_this._defaultModel);
  71138. if (meshLoaded) {
  71139. meshLoaded(_this._defaultModel);
  71140. }
  71141. }, null, function (scene, message) {
  71142. BABYLON.Tools.Log(message);
  71143. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71144. if (!forceDefault) {
  71145. _this.initControllerMesh(scene, meshLoaded, true);
  71146. }
  71147. });
  71148. };
  71149. /**
  71150. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71151. * can be transformed by button presses and axes values, based on this._mapping.
  71152. *
  71153. * @param scene scene in which the meshes exist
  71154. * @param meshes list of meshes that make up the controller model to process
  71155. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71156. */
  71157. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71158. var loadedMeshInfo = null;
  71159. // Create a new mesh to contain the glTF hierarchy
  71160. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71161. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71162. var childMesh = null;
  71163. for (var i = 0; i < meshes.length; i++) {
  71164. var mesh = meshes[i];
  71165. if (!mesh.parent) {
  71166. // Exclude controller meshes from picking results
  71167. mesh.isPickable = false;
  71168. // Handle root node, attach to the new parentMesh
  71169. childMesh = mesh;
  71170. break;
  71171. }
  71172. }
  71173. if (childMesh) {
  71174. childMesh.setParent(parentMesh);
  71175. // Create our mesh info. Note that this method will always return non-null.
  71176. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71177. }
  71178. else {
  71179. BABYLON.Tools.Warn('Could not find root node in model file.');
  71180. }
  71181. return loadedMeshInfo;
  71182. };
  71183. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71184. var loadedMeshInfo = new LoadedMeshInfo();
  71185. var i;
  71186. loadedMeshInfo.rootNode = rootNode;
  71187. // Reset the caches
  71188. loadedMeshInfo.buttonMeshes = {};
  71189. loadedMeshInfo.axisMeshes = {};
  71190. // Button Meshes
  71191. for (i = 0; i < this._mapping.buttons.length; i++) {
  71192. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71193. if (!buttonMeshName) {
  71194. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71195. continue;
  71196. }
  71197. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71198. if (!buttonMesh) {
  71199. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71200. continue;
  71201. }
  71202. var buttonMeshInfo = {
  71203. index: i,
  71204. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71205. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71206. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71207. };
  71208. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71209. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71210. }
  71211. else {
  71212. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71213. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71214. '(VALUE: ' + !!buttonMeshInfo.value +
  71215. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71216. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71217. ')');
  71218. }
  71219. }
  71220. // Axis Meshes
  71221. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71222. var axisMeshName = this._mapping.axisMeshNames[i];
  71223. if (!axisMeshName) {
  71224. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71225. continue;
  71226. }
  71227. var axisMesh = getChildByName(rootNode, axisMeshName);
  71228. if (!axisMesh) {
  71229. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71230. continue;
  71231. }
  71232. var axisMeshInfo = {
  71233. index: i,
  71234. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71235. min: getImmediateChildByName(axisMesh, 'MIN'),
  71236. max: getImmediateChildByName(axisMesh, 'MAX')
  71237. };
  71238. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71239. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71240. }
  71241. else {
  71242. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71243. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71244. '(VALUE: ' + !!axisMeshInfo.value +
  71245. ', MIN: ' + !!axisMeshInfo.min +
  71246. ', MAX:' + !!axisMeshInfo.max +
  71247. ')');
  71248. }
  71249. }
  71250. // Pointing Ray
  71251. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71252. if (!loadedMeshInfo.pointingPoseNode) {
  71253. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71254. }
  71255. return loadedMeshInfo;
  71256. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71257. function getChildByName(node, name) {
  71258. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71259. }
  71260. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71261. function getImmediateChildByName(node, name) {
  71262. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71263. }
  71264. };
  71265. /**
  71266. * Gets the ray of the controller in the direction the controller is pointing
  71267. * @param length the length the resulting ray should be
  71268. * @returns a ray in the direction the controller is pointing
  71269. */
  71270. WindowsMotionController.prototype.getForwardRay = function (length) {
  71271. if (length === void 0) { length = 100; }
  71272. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71273. return _super.prototype.getForwardRay.call(this, length);
  71274. }
  71275. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71276. var origin = m.getTranslation();
  71277. var forward = new BABYLON.Vector3(0, 0, -1);
  71278. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71279. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71280. return new BABYLON.Ray(origin, direction, length);
  71281. };
  71282. /**
  71283. * Disposes of the controller
  71284. */
  71285. WindowsMotionController.prototype.dispose = function () {
  71286. _super.prototype.dispose.call(this);
  71287. this.onTrackpadChangedObservable.clear();
  71288. };
  71289. /**
  71290. * The base url used to load the left and right controller models
  71291. */
  71292. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71293. /**
  71294. * The name of the left controller model file
  71295. */
  71296. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71297. /**
  71298. * The name of the right controller model file
  71299. */
  71300. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71301. /**
  71302. * The controller name prefix for this controller type
  71303. */
  71304. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71305. /**
  71306. * The controller id pattern for this controller type
  71307. */
  71308. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71309. return WindowsMotionController;
  71310. }(BABYLON.WebVRController));
  71311. BABYLON.WindowsMotionController = WindowsMotionController;
  71312. })(BABYLON || (BABYLON = {}));
  71313. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71314. var BABYLON;
  71315. (function (BABYLON) {
  71316. /**
  71317. * Gear VR Controller
  71318. */
  71319. var GearVRController = /** @class */ (function (_super) {
  71320. __extends(GearVRController, _super);
  71321. /**
  71322. * Creates a new GearVRController from a gamepad
  71323. * @param vrGamepad the gamepad that the controller should be created from
  71324. */
  71325. function GearVRController(vrGamepad) {
  71326. var _this = _super.call(this, vrGamepad) || this;
  71327. _this._buttonIndexToObservableNameMap = [
  71328. 'onTrackpadChangedObservable',
  71329. 'onTriggerStateChangedObservable' // Trigger
  71330. ];
  71331. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71332. return _this;
  71333. }
  71334. /**
  71335. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71336. * @param scene scene in which to add meshes
  71337. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71338. */
  71339. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71340. var _this = this;
  71341. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71342. _this._defaultModel = newMeshes[1];
  71343. _this.attachToMesh(_this._defaultModel);
  71344. if (meshLoaded) {
  71345. meshLoaded(_this._defaultModel);
  71346. }
  71347. });
  71348. };
  71349. /**
  71350. * Called once for each button that changed state since the last frame
  71351. * @param buttonIdx Which button index changed
  71352. * @param state New state of the button
  71353. * @param changes Which properties on the state changed since last frame
  71354. */
  71355. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71356. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71357. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71358. // Only emit events for buttons that we know how to map from index to observable
  71359. var observable = this[observableName];
  71360. if (observable) {
  71361. observable.notifyObservers(state);
  71362. }
  71363. }
  71364. };
  71365. /**
  71366. * Base Url for the controller model.
  71367. */
  71368. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71369. /**
  71370. * File name for the controller model.
  71371. */
  71372. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71373. /**
  71374. * Gamepad Id prefix used to identify this controller.
  71375. */
  71376. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71377. return GearVRController;
  71378. }(BABYLON.WebVRController));
  71379. BABYLON.GearVRController = GearVRController;
  71380. })(BABYLON || (BABYLON = {}));
  71381. //# sourceMappingURL=babylon.gearVRController.js.map
  71382. var BABYLON;
  71383. (function (BABYLON) {
  71384. /**
  71385. * Google Daydream controller
  71386. */
  71387. var DaydreamController = /** @class */ (function (_super) {
  71388. __extends(DaydreamController, _super);
  71389. /**
  71390. * Creates a new DaydreamController from a gamepad
  71391. * @param vrGamepad the gamepad that the controller should be created from
  71392. */
  71393. function DaydreamController(vrGamepad) {
  71394. var _this = _super.call(this, vrGamepad) || this;
  71395. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71396. return _this;
  71397. }
  71398. /**
  71399. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71400. * @param scene scene in which to add meshes
  71401. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71402. */
  71403. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71404. var _this = this;
  71405. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71406. _this._defaultModel = newMeshes[1];
  71407. _this.attachToMesh(_this._defaultModel);
  71408. if (meshLoaded) {
  71409. meshLoaded(_this._defaultModel);
  71410. }
  71411. });
  71412. };
  71413. /**
  71414. * Called once for each button that changed state since the last frame
  71415. * @param buttonIdx Which button index changed
  71416. * @param state New state of the button
  71417. * @param changes Which properties on the state changed since last frame
  71418. */
  71419. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71420. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71421. if (buttonIdx === 0) {
  71422. var observable = this.onTriggerStateChangedObservable;
  71423. if (observable) {
  71424. observable.notifyObservers(state);
  71425. }
  71426. }
  71427. else {
  71428. // If the app or home buttons are ever made available
  71429. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71430. }
  71431. };
  71432. /**
  71433. * Base Url for the controller model.
  71434. */
  71435. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71436. /**
  71437. * File name for the controller model.
  71438. */
  71439. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71440. /**
  71441. * Gamepad Id prefix used to identify Daydream Controller.
  71442. */
  71443. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71444. return DaydreamController;
  71445. }(BABYLON.WebVRController));
  71446. BABYLON.DaydreamController = DaydreamController;
  71447. })(BABYLON || (BABYLON = {}));
  71448. //# sourceMappingURL=babylon.daydreamController.js.map
  71449. var BABYLON;
  71450. (function (BABYLON) {
  71451. var FollowCamera = /** @class */ (function (_super) {
  71452. __extends(FollowCamera, _super);
  71453. function FollowCamera(name, position, scene, lockedTarget) {
  71454. if (lockedTarget === void 0) { lockedTarget = null; }
  71455. var _this = _super.call(this, name, position, scene) || this;
  71456. _this.radius = 12;
  71457. _this.rotationOffset = 0;
  71458. _this.heightOffset = 4;
  71459. _this.cameraAcceleration = 0.05;
  71460. _this.maxCameraSpeed = 20;
  71461. _this.lockedTarget = lockedTarget;
  71462. return _this;
  71463. }
  71464. FollowCamera.prototype.getRadians = function (degrees) {
  71465. return degrees * Math.PI / 180;
  71466. };
  71467. FollowCamera.prototype.follow = function (cameraTarget) {
  71468. if (!cameraTarget)
  71469. return;
  71470. var yRotation;
  71471. if (cameraTarget.rotationQuaternion) {
  71472. var rotMatrix = new BABYLON.Matrix();
  71473. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71474. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71475. }
  71476. else {
  71477. yRotation = cameraTarget.rotation.y;
  71478. }
  71479. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71480. var targetPosition = cameraTarget.getAbsolutePosition();
  71481. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71482. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71483. var dx = targetX - this.position.x;
  71484. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71485. var dz = (targetZ) - this.position.z;
  71486. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71487. var vy = dy * this.cameraAcceleration;
  71488. var vz = dz * this.cameraAcceleration * 2;
  71489. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71490. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71491. }
  71492. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71493. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71494. }
  71495. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71496. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71497. }
  71498. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71499. this.setTarget(targetPosition);
  71500. };
  71501. FollowCamera.prototype._checkInputs = function () {
  71502. _super.prototype._checkInputs.call(this);
  71503. if (this.lockedTarget) {
  71504. this.follow(this.lockedTarget);
  71505. }
  71506. };
  71507. FollowCamera.prototype.getClassName = function () {
  71508. return "FollowCamera";
  71509. };
  71510. __decorate([
  71511. BABYLON.serialize()
  71512. ], FollowCamera.prototype, "radius", void 0);
  71513. __decorate([
  71514. BABYLON.serialize()
  71515. ], FollowCamera.prototype, "rotationOffset", void 0);
  71516. __decorate([
  71517. BABYLON.serialize()
  71518. ], FollowCamera.prototype, "heightOffset", void 0);
  71519. __decorate([
  71520. BABYLON.serialize()
  71521. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71522. __decorate([
  71523. BABYLON.serialize()
  71524. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71525. __decorate([
  71526. BABYLON.serializeAsMeshReference("lockedTargetId")
  71527. ], FollowCamera.prototype, "lockedTarget", void 0);
  71528. return FollowCamera;
  71529. }(BABYLON.TargetCamera));
  71530. BABYLON.FollowCamera = FollowCamera;
  71531. var ArcFollowCamera = /** @class */ (function (_super) {
  71532. __extends(ArcFollowCamera, _super);
  71533. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71534. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71535. _this.alpha = alpha;
  71536. _this.beta = beta;
  71537. _this.radius = radius;
  71538. _this.target = target;
  71539. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71540. _this.follow();
  71541. return _this;
  71542. }
  71543. ArcFollowCamera.prototype.follow = function () {
  71544. if (!this.target) {
  71545. return;
  71546. }
  71547. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71548. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71549. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71550. var targetPosition = this.target.getAbsolutePosition();
  71551. this.position = targetPosition.add(this._cartesianCoordinates);
  71552. this.setTarget(targetPosition);
  71553. };
  71554. ArcFollowCamera.prototype._checkInputs = function () {
  71555. _super.prototype._checkInputs.call(this);
  71556. this.follow();
  71557. };
  71558. ArcFollowCamera.prototype.getClassName = function () {
  71559. return "ArcFollowCamera";
  71560. };
  71561. return ArcFollowCamera;
  71562. }(BABYLON.TargetCamera));
  71563. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71564. })(BABYLON || (BABYLON = {}));
  71565. //# sourceMappingURL=babylon.followCamera.js.map
  71566. var BABYLON;
  71567. (function (BABYLON) {
  71568. // We're mainly based on the logic defined into the FreeCamera code
  71569. var UniversalCamera = /** @class */ (function (_super) {
  71570. __extends(UniversalCamera, _super);
  71571. //-- end properties for backward compatibility for inputs
  71572. function UniversalCamera(name, position, scene) {
  71573. var _this = _super.call(this, name, position, scene) || this;
  71574. _this.inputs.addGamepad();
  71575. return _this;
  71576. }
  71577. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71578. //-- Begin properties for backward compatibility for inputs
  71579. get: function () {
  71580. var gamepad = this.inputs.attached["gamepad"];
  71581. if (gamepad)
  71582. return gamepad.gamepadAngularSensibility;
  71583. return 0;
  71584. },
  71585. set: function (value) {
  71586. var gamepad = this.inputs.attached["gamepad"];
  71587. if (gamepad)
  71588. gamepad.gamepadAngularSensibility = value;
  71589. },
  71590. enumerable: true,
  71591. configurable: true
  71592. });
  71593. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71594. get: function () {
  71595. var gamepad = this.inputs.attached["gamepad"];
  71596. if (gamepad)
  71597. return gamepad.gamepadMoveSensibility;
  71598. return 0;
  71599. },
  71600. set: function (value) {
  71601. var gamepad = this.inputs.attached["gamepad"];
  71602. if (gamepad)
  71603. gamepad.gamepadMoveSensibility = value;
  71604. },
  71605. enumerable: true,
  71606. configurable: true
  71607. });
  71608. UniversalCamera.prototype.getClassName = function () {
  71609. return "UniversalCamera";
  71610. };
  71611. return UniversalCamera;
  71612. }(BABYLON.TouchCamera));
  71613. BABYLON.UniversalCamera = UniversalCamera;
  71614. })(BABYLON || (BABYLON = {}));
  71615. //# sourceMappingURL=babylon.universalCamera.js.map
  71616. var BABYLON;
  71617. (function (BABYLON) {
  71618. // We're mainly based on the logic defined into the FreeCamera code
  71619. var GamepadCamera = /** @class */ (function (_super) {
  71620. __extends(GamepadCamera, _super);
  71621. //-- end properties for backward compatibility for inputs
  71622. function GamepadCamera(name, position, scene) {
  71623. return _super.call(this, name, position, scene) || this;
  71624. }
  71625. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71626. //-- Begin properties for backward compatibility for inputs
  71627. get: function () {
  71628. var gamepad = this.inputs.attached["gamepad"];
  71629. if (gamepad)
  71630. return gamepad.gamepadAngularSensibility;
  71631. return 0;
  71632. },
  71633. set: function (value) {
  71634. var gamepad = this.inputs.attached["gamepad"];
  71635. if (gamepad)
  71636. gamepad.gamepadAngularSensibility = value;
  71637. },
  71638. enumerable: true,
  71639. configurable: true
  71640. });
  71641. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71642. get: function () {
  71643. var gamepad = this.inputs.attached["gamepad"];
  71644. if (gamepad)
  71645. return gamepad.gamepadMoveSensibility;
  71646. return 0;
  71647. },
  71648. set: function (value) {
  71649. var gamepad = this.inputs.attached["gamepad"];
  71650. if (gamepad)
  71651. gamepad.gamepadMoveSensibility = value;
  71652. },
  71653. enumerable: true,
  71654. configurable: true
  71655. });
  71656. GamepadCamera.prototype.getClassName = function () {
  71657. return "GamepadCamera";
  71658. };
  71659. return GamepadCamera;
  71660. }(BABYLON.UniversalCamera));
  71661. BABYLON.GamepadCamera = GamepadCamera;
  71662. })(BABYLON || (BABYLON = {}));
  71663. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71664. var BABYLON;
  71665. (function (BABYLON) {
  71666. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71667. function PostProcessRenderPipelineManager() {
  71668. this._renderPipelines = {};
  71669. }
  71670. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71671. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71672. };
  71673. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71674. if (unique === void 0) { unique = false; }
  71675. var renderPipeline = this._renderPipelines[renderPipelineName];
  71676. if (!renderPipeline) {
  71677. return;
  71678. }
  71679. renderPipeline._attachCameras(cameras, unique);
  71680. };
  71681. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71682. var renderPipeline = this._renderPipelines[renderPipelineName];
  71683. if (!renderPipeline) {
  71684. return;
  71685. }
  71686. renderPipeline._detachCameras(cameras);
  71687. };
  71688. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71689. var renderPipeline = this._renderPipelines[renderPipelineName];
  71690. if (!renderPipeline) {
  71691. return;
  71692. }
  71693. renderPipeline._enableEffect(renderEffectName, cameras);
  71694. };
  71695. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71696. var renderPipeline = this._renderPipelines[renderPipelineName];
  71697. if (!renderPipeline) {
  71698. return;
  71699. }
  71700. renderPipeline._disableEffect(renderEffectName, cameras);
  71701. };
  71702. PostProcessRenderPipelineManager.prototype.update = function () {
  71703. for (var renderPipelineName in this._renderPipelines) {
  71704. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71705. var pipeline = this._renderPipelines[renderPipelineName];
  71706. if (!pipeline.isSupported) {
  71707. pipeline.dispose();
  71708. delete this._renderPipelines[renderPipelineName];
  71709. }
  71710. else {
  71711. pipeline._update();
  71712. }
  71713. }
  71714. }
  71715. };
  71716. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71717. for (var renderPipelineName in this._renderPipelines) {
  71718. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71719. var pipeline = this._renderPipelines[renderPipelineName];
  71720. pipeline._rebuild();
  71721. }
  71722. }
  71723. };
  71724. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71725. for (var renderPipelineName in this._renderPipelines) {
  71726. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71727. var pipeline = this._renderPipelines[renderPipelineName];
  71728. pipeline.dispose();
  71729. }
  71730. }
  71731. };
  71732. return PostProcessRenderPipelineManager;
  71733. }());
  71734. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71735. })(BABYLON || (BABYLON = {}));
  71736. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71737. var BABYLON;
  71738. (function (BABYLON) {
  71739. /**
  71740. * This represents a set of one or more post processes in Babylon.
  71741. * A post process can be used to apply a shader to a texture after it is rendered.
  71742. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71743. */
  71744. var PostProcessRenderEffect = /** @class */ (function () {
  71745. /**
  71746. * Instantiates a post process render effect.
  71747. * A post process can be used to apply a shader to a texture after it is rendered.
  71748. * @param engine The engine the effect is tied to
  71749. * @param name The name of the effect
  71750. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71751. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71752. */
  71753. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71754. this._name = name;
  71755. this._singleInstance = singleInstance || true;
  71756. this._getPostProcesses = getPostProcesses;
  71757. this._cameras = {};
  71758. this._indicesForCamera = {};
  71759. this._postProcesses = {};
  71760. }
  71761. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71762. /**
  71763. * Checks if all the post processes in the effect are supported.
  71764. */
  71765. get: function () {
  71766. for (var index in this._postProcesses) {
  71767. if (this._postProcesses.hasOwnProperty(index)) {
  71768. var pps = this._postProcesses[index];
  71769. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71770. if (!pps[ppIndex].isSupported) {
  71771. return false;
  71772. }
  71773. }
  71774. }
  71775. }
  71776. return true;
  71777. },
  71778. enumerable: true,
  71779. configurable: true
  71780. });
  71781. /**
  71782. * Updates the current state of the effect
  71783. */
  71784. PostProcessRenderEffect.prototype._update = function () {
  71785. };
  71786. /**
  71787. * Attaches the effect on cameras
  71788. * @param cameras The camera to attach to.
  71789. */
  71790. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71791. var _this = this;
  71792. var cameraKey;
  71793. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71794. if (!cams) {
  71795. return;
  71796. }
  71797. for (var i = 0; i < cams.length; i++) {
  71798. var camera = cams[i];
  71799. var cameraName = camera.name;
  71800. if (this._singleInstance) {
  71801. cameraKey = 0;
  71802. }
  71803. else {
  71804. cameraKey = cameraName;
  71805. }
  71806. if (!this._postProcesses[cameraKey]) {
  71807. var postProcess = this._getPostProcesses();
  71808. if (postProcess) {
  71809. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71810. }
  71811. }
  71812. if (!this._indicesForCamera[cameraName]) {
  71813. this._indicesForCamera[cameraName] = [];
  71814. }
  71815. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71816. var index = camera.attachPostProcess(postProcess);
  71817. _this._indicesForCamera[cameraName].push(index);
  71818. });
  71819. if (!this._cameras[cameraName]) {
  71820. this._cameras[cameraName] = camera;
  71821. }
  71822. }
  71823. };
  71824. /**
  71825. * Detatches the effect on cameras
  71826. * @param cameras The camera to detatch from.
  71827. */
  71828. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71829. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71830. if (!cams) {
  71831. return;
  71832. }
  71833. for (var i = 0; i < cams.length; i++) {
  71834. var camera = cams[i];
  71835. var cameraName = camera.name;
  71836. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71837. camera.detachPostProcess(postProcess);
  71838. });
  71839. if (this._cameras[cameraName]) {
  71840. //this._indicesForCamera.splice(index, 1);
  71841. this._cameras[cameraName] = null;
  71842. }
  71843. }
  71844. };
  71845. /**
  71846. * Enables the effect on given cameras
  71847. * @param cameras The camera to enable.
  71848. */
  71849. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71850. var _this = this;
  71851. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71852. if (!cams) {
  71853. return;
  71854. }
  71855. for (var i = 0; i < cams.length; i++) {
  71856. var camera = cams[i];
  71857. var cameraName = camera.name;
  71858. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71859. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71860. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71861. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  71862. });
  71863. }
  71864. }
  71865. }
  71866. };
  71867. /**
  71868. * Disables the effect on the given cameras
  71869. * @param cameras The camera to disable.
  71870. */
  71871. PostProcessRenderEffect.prototype._disable = function (cameras) {
  71872. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71873. if (!cams) {
  71874. return;
  71875. }
  71876. for (var i = 0; i < cams.length; i++) {
  71877. var camera = cams[i];
  71878. var cameraName = camera.name;
  71879. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71880. camera.detachPostProcess(postProcess);
  71881. });
  71882. }
  71883. };
  71884. /**
  71885. * Gets a list of the post processes contained in the effect.
  71886. * @param camera The camera to get the post processes on.
  71887. * @returns The list of the post processes in the effect.
  71888. */
  71889. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  71890. if (this._singleInstance) {
  71891. return this._postProcesses[0];
  71892. }
  71893. else {
  71894. if (!camera) {
  71895. return null;
  71896. }
  71897. return this._postProcesses[camera.name];
  71898. }
  71899. };
  71900. return PostProcessRenderEffect;
  71901. }());
  71902. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  71903. })(BABYLON || (BABYLON = {}));
  71904. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  71905. var BABYLON;
  71906. (function (BABYLON) {
  71907. var PostProcessRenderPipeline = /** @class */ (function () {
  71908. function PostProcessRenderPipeline(engine, name) {
  71909. this.engine = engine;
  71910. this._name = name;
  71911. this._renderEffects = {};
  71912. this._renderEffectsForIsolatedPass = new Array();
  71913. this._cameras = [];
  71914. }
  71915. PostProcessRenderPipeline.prototype.getClassName = function () {
  71916. return "PostProcessRenderPipeline";
  71917. };
  71918. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  71919. get: function () {
  71920. for (var renderEffectName in this._renderEffects) {
  71921. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71922. if (!this._renderEffects[renderEffectName].isSupported) {
  71923. return false;
  71924. }
  71925. }
  71926. }
  71927. return true;
  71928. },
  71929. enumerable: true,
  71930. configurable: true
  71931. });
  71932. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  71933. this._renderEffects[renderEffect._name] = renderEffect;
  71934. };
  71935. // private
  71936. PostProcessRenderPipeline.prototype._rebuild = function () {
  71937. };
  71938. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  71939. var renderEffects = this._renderEffects[renderEffectName];
  71940. if (!renderEffects) {
  71941. return;
  71942. }
  71943. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71944. };
  71945. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  71946. var renderEffects = this._renderEffects[renderEffectName];
  71947. if (!renderEffects) {
  71948. return;
  71949. }
  71950. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  71951. };
  71952. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  71953. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71954. if (!cams) {
  71955. return;
  71956. }
  71957. var indicesToDelete = [];
  71958. var i;
  71959. for (i = 0; i < cams.length; i++) {
  71960. var camera = cams[i];
  71961. var cameraName = camera.name;
  71962. if (this._cameras.indexOf(camera) === -1) {
  71963. this._cameras[cameraName] = camera;
  71964. }
  71965. else if (unique) {
  71966. indicesToDelete.push(i);
  71967. }
  71968. }
  71969. for (i = 0; i < indicesToDelete.length; i++) {
  71970. cameras.splice(indicesToDelete[i], 1);
  71971. }
  71972. for (var renderEffectName in this._renderEffects) {
  71973. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71974. this._renderEffects[renderEffectName]._attachCameras(cams);
  71975. }
  71976. }
  71977. };
  71978. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  71979. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71980. if (!cams) {
  71981. return;
  71982. }
  71983. for (var renderEffectName in this._renderEffects) {
  71984. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71985. this._renderEffects[renderEffectName]._detachCameras(cams);
  71986. }
  71987. }
  71988. for (var i = 0; i < cams.length; i++) {
  71989. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  71990. }
  71991. };
  71992. PostProcessRenderPipeline.prototype._update = function () {
  71993. for (var renderEffectName in this._renderEffects) {
  71994. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  71995. this._renderEffects[renderEffectName]._update();
  71996. }
  71997. }
  71998. for (var i = 0; i < this._cameras.length; i++) {
  71999. var cameraName = this._cameras[i].name;
  72000. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72001. this._renderEffectsForIsolatedPass[cameraName]._update();
  72002. }
  72003. }
  72004. };
  72005. PostProcessRenderPipeline.prototype._reset = function () {
  72006. this._renderEffects = {};
  72007. this._renderEffectsForIsolatedPass = new Array();
  72008. };
  72009. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72010. // 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)
  72011. var effectKeys = Object.keys(this._renderEffects);
  72012. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72013. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72014. if (postProcesses) {
  72015. postProcesses[0].samples = sampleCount;
  72016. return true;
  72017. }
  72018. }
  72019. return false;
  72020. };
  72021. PostProcessRenderPipeline.prototype.dispose = function () {
  72022. // Must be implemented by children
  72023. };
  72024. __decorate([
  72025. BABYLON.serialize()
  72026. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72027. return PostProcessRenderPipeline;
  72028. }());
  72029. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72030. })(BABYLON || (BABYLON = {}));
  72031. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72032. var BABYLON;
  72033. (function (BABYLON) {
  72034. /**
  72035. * This represents a depth renderer in Babylon.
  72036. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72037. */
  72038. var DepthRenderer = /** @class */ (function () {
  72039. /**
  72040. * Instantiates a depth renderer
  72041. * @param scene The scene the renderer belongs to
  72042. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72043. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72044. */
  72045. function DepthRenderer(scene, type, camera) {
  72046. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72047. if (camera === void 0) { camera = null; }
  72048. var _this = this;
  72049. this._scene = scene;
  72050. this._camera = camera;
  72051. var engine = scene.getEngine();
  72052. // Render target
  72053. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72054. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72055. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72056. this._depthMap.refreshRate = 1;
  72057. this._depthMap.renderParticles = false;
  72058. this._depthMap.renderList = null;
  72059. // Camera to get depth map from to support multiple concurrent cameras
  72060. this._depthMap.activeCamera = this._camera;
  72061. this._depthMap.ignoreCameraViewport = true;
  72062. this._depthMap.useCameraPostProcesses = false;
  72063. // set default depth value to 1.0 (far away)
  72064. this._depthMap.onClearObservable.add(function (engine) {
  72065. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72066. });
  72067. // Custom render function
  72068. var renderSubMesh = function (subMesh) {
  72069. var mesh = subMesh.getRenderingMesh();
  72070. var scene = _this._scene;
  72071. var engine = scene.getEngine();
  72072. var material = subMesh.getMaterial();
  72073. if (!material) {
  72074. return;
  72075. }
  72076. // Culling and reverse (right handed system)
  72077. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72078. // Managing instances
  72079. var batch = mesh._getInstancesRenderList(subMesh._id);
  72080. if (batch.mustReturn) {
  72081. return;
  72082. }
  72083. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72084. var camera = _this._camera || scene.activeCamera;
  72085. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72086. engine.enableEffect(_this._effect);
  72087. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72088. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72089. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72090. // Alpha test
  72091. if (material && material.needAlphaTesting()) {
  72092. var alphaTexture = material.getAlphaTestTexture();
  72093. if (alphaTexture) {
  72094. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72095. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72096. }
  72097. }
  72098. // Bones
  72099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72100. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72101. }
  72102. // Draw
  72103. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72104. }
  72105. };
  72106. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72107. var index;
  72108. if (depthOnlySubMeshes.length) {
  72109. engine.setColorWrite(false);
  72110. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72111. renderSubMesh(depthOnlySubMeshes.data[index]);
  72112. }
  72113. engine.setColorWrite(true);
  72114. }
  72115. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72116. renderSubMesh(opaqueSubMeshes.data[index]);
  72117. }
  72118. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72119. renderSubMesh(alphaTestSubMeshes.data[index]);
  72120. }
  72121. };
  72122. }
  72123. /**
  72124. * Creates the depth rendering effect and checks if the effect is ready.
  72125. * @param subMesh The submesh to be used to render the depth map of
  72126. * @param useInstances If multiple world instances should be used
  72127. * @returns if the depth renderer is ready to render the depth map
  72128. */
  72129. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72130. var material = subMesh.getMaterial();
  72131. if (material.disableDepthWrite) {
  72132. return false;
  72133. }
  72134. var defines = [];
  72135. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72136. var mesh = subMesh.getMesh();
  72137. // Alpha test
  72138. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72139. defines.push("#define ALPHATEST");
  72140. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72141. attribs.push(BABYLON.VertexBuffer.UVKind);
  72142. defines.push("#define UV1");
  72143. }
  72144. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72145. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72146. defines.push("#define UV2");
  72147. }
  72148. }
  72149. // Bones
  72150. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72151. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72152. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72153. if (mesh.numBoneInfluencers > 4) {
  72154. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72155. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72156. }
  72157. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72158. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72159. }
  72160. else {
  72161. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72162. }
  72163. // Instances
  72164. if (useInstances) {
  72165. defines.push("#define INSTANCES");
  72166. attribs.push("world0");
  72167. attribs.push("world1");
  72168. attribs.push("world2");
  72169. attribs.push("world3");
  72170. }
  72171. // Get correct effect
  72172. var join = defines.join("\n");
  72173. if (this._cachedDefines !== join) {
  72174. this._cachedDefines = join;
  72175. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72176. }
  72177. return this._effect.isReady();
  72178. };
  72179. /**
  72180. * Gets the texture which the depth map will be written to.
  72181. * @returns The depth map texture
  72182. */
  72183. DepthRenderer.prototype.getDepthMap = function () {
  72184. return this._depthMap;
  72185. };
  72186. /**
  72187. * Disposes of the depth renderer.
  72188. */
  72189. DepthRenderer.prototype.dispose = function () {
  72190. this._depthMap.dispose();
  72191. };
  72192. return DepthRenderer;
  72193. }());
  72194. BABYLON.DepthRenderer = DepthRenderer;
  72195. })(BABYLON || (BABYLON = {}));
  72196. //# sourceMappingURL=babylon.depthRenderer.js.map
  72197. var BABYLON;
  72198. (function (BABYLON) {
  72199. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72200. __extends(SSAORenderingPipeline, _super);
  72201. /**
  72202. * @constructor
  72203. * @param {string} name - The rendering pipeline name
  72204. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72205. * @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 }
  72206. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72207. */
  72208. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72209. var _this = _super.call(this, scene.getEngine(), name) || this;
  72210. // Members
  72211. /**
  72212. * The PassPostProcess id in the pipeline that contains the original scene color
  72213. */
  72214. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72215. /**
  72216. * The SSAO PostProcess id in the pipeline
  72217. */
  72218. _this.SSAORenderEffect = "SSAORenderEffect";
  72219. /**
  72220. * The horizontal blur PostProcess id in the pipeline
  72221. */
  72222. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72223. /**
  72224. * The vertical blur PostProcess id in the pipeline
  72225. */
  72226. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72227. /**
  72228. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72229. */
  72230. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72231. /**
  72232. * The output strength of the SSAO post-process. Default value is 1.0.
  72233. */
  72234. _this.totalStrength = 1.0;
  72235. /**
  72236. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72237. */
  72238. _this.radius = 0.0001;
  72239. /**
  72240. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72241. * Must not be equal to fallOff and superior to fallOff.
  72242. * Default value is 0.975
  72243. */
  72244. _this.area = 0.0075;
  72245. /**
  72246. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72247. * Must not be equal to area and inferior to area.
  72248. * Default value is 0.0
  72249. */
  72250. _this.fallOff = 0.000001;
  72251. /**
  72252. * The base color of the SSAO post-process
  72253. * The final result is "base + ssao" between [0, 1]
  72254. */
  72255. _this.base = 0.5;
  72256. _this._firstUpdate = true;
  72257. _this._scene = scene;
  72258. // Set up assets
  72259. _this._createRandomTexture();
  72260. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72261. var ssaoRatio = ratio.ssaoRatio || ratio;
  72262. var combineRatio = ratio.combineRatio || ratio;
  72263. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72264. _this._createSSAOPostProcess(ssaoRatio);
  72265. _this._createBlurPostProcess(ssaoRatio);
  72266. _this._createSSAOCombinePostProcess(combineRatio);
  72267. // Set up pipeline
  72268. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72269. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72270. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72271. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72272. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72273. // Finish
  72274. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72275. if (cameras)
  72276. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72277. return _this;
  72278. }
  72279. // Public Methods
  72280. /**
  72281. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72282. */
  72283. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72284. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72285. for (var i = 0; i < this._scene.cameras.length; i++) {
  72286. var camera = this._scene.cameras[i];
  72287. this._originalColorPostProcess.dispose(camera);
  72288. this._ssaoPostProcess.dispose(camera);
  72289. this._blurHPostProcess.dispose(camera);
  72290. this._blurVPostProcess.dispose(camera);
  72291. this._ssaoCombinePostProcess.dispose(camera);
  72292. }
  72293. this._randomTexture.dispose();
  72294. if (disableDepthRender)
  72295. this._scene.disableDepthRenderer();
  72296. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72297. _super.prototype.dispose.call(this);
  72298. };
  72299. // Private Methods
  72300. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72301. var _this = this;
  72302. var size = 16;
  72303. 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);
  72304. 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);
  72305. this._blurHPostProcess.onActivateObservable.add(function () {
  72306. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72307. _this._blurHPostProcess.kernel = size * dw;
  72308. });
  72309. this._blurVPostProcess.onActivateObservable.add(function () {
  72310. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72311. _this._blurVPostProcess.kernel = size * dw;
  72312. });
  72313. };
  72314. SSAORenderingPipeline.prototype._rebuild = function () {
  72315. this._firstUpdate = true;
  72316. _super.prototype._rebuild.call(this);
  72317. };
  72318. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72319. var _this = this;
  72320. var numSamples = 16;
  72321. var sampleSphere = [
  72322. 0.5381, 0.1856, -0.4319,
  72323. 0.1379, 0.2486, 0.4430,
  72324. 0.3371, 0.5679, -0.0057,
  72325. -0.6999, -0.0451, -0.0019,
  72326. 0.0689, -0.1598, -0.8547,
  72327. 0.0560, 0.0069, -0.1843,
  72328. -0.0146, 0.1402, 0.0762,
  72329. 0.0100, -0.1924, -0.0344,
  72330. -0.3577, -0.5301, -0.4358,
  72331. -0.3169, 0.1063, 0.0158,
  72332. 0.0103, -0.5869, 0.0046,
  72333. -0.0897, -0.4940, 0.3287,
  72334. 0.7119, -0.0154, -0.0918,
  72335. -0.0533, 0.0596, -0.5411,
  72336. 0.0352, -0.0631, 0.5460,
  72337. -0.4776, 0.2847, -0.0271
  72338. ];
  72339. var samplesFactor = 1.0 / numSamples;
  72340. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72341. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72342. "area", "fallOff", "base", "range", "viewport"
  72343. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72344. this._ssaoPostProcess.onApply = function (effect) {
  72345. if (_this._firstUpdate) {
  72346. effect.setArray3("sampleSphere", sampleSphere);
  72347. effect.setFloat("samplesFactor", samplesFactor);
  72348. effect.setFloat("randTextureTiles", 4.0);
  72349. }
  72350. effect.setFloat("totalStrength", _this.totalStrength);
  72351. effect.setFloat("radius", _this.radius);
  72352. effect.setFloat("area", _this.area);
  72353. effect.setFloat("fallOff", _this.fallOff);
  72354. effect.setFloat("base", _this.base);
  72355. effect.setTexture("textureSampler", _this._depthTexture);
  72356. effect.setTexture("randomSampler", _this._randomTexture);
  72357. };
  72358. };
  72359. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72360. var _this = this;
  72361. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72362. this._ssaoCombinePostProcess.onApply = function (effect) {
  72363. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72364. };
  72365. };
  72366. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72367. var size = 512;
  72368. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72369. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72370. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72371. var context = this._randomTexture.getContext();
  72372. var rand = function (min, max) {
  72373. return Math.random() * (max - min) + min;
  72374. };
  72375. var randVector = BABYLON.Vector3.Zero();
  72376. for (var x = 0; x < size; x++) {
  72377. for (var y = 0; y < size; y++) {
  72378. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72379. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72380. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72381. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72382. context.fillRect(x, y, 1, 1);
  72383. }
  72384. }
  72385. this._randomTexture.update(false);
  72386. };
  72387. __decorate([
  72388. BABYLON.serialize()
  72389. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72390. __decorate([
  72391. BABYLON.serialize()
  72392. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72393. __decorate([
  72394. BABYLON.serialize()
  72395. ], SSAORenderingPipeline.prototype, "area", void 0);
  72396. __decorate([
  72397. BABYLON.serialize()
  72398. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72399. __decorate([
  72400. BABYLON.serialize()
  72401. ], SSAORenderingPipeline.prototype, "base", void 0);
  72402. return SSAORenderingPipeline;
  72403. }(BABYLON.PostProcessRenderPipeline));
  72404. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72405. })(BABYLON || (BABYLON = {}));
  72406. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72407. var BABYLON;
  72408. (function (BABYLON) {
  72409. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72410. __extends(SSAO2RenderingPipeline, _super);
  72411. /**
  72412. * @constructor
  72413. * @param {string} name - The rendering pipeline name
  72414. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72415. * @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 }
  72416. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72417. */
  72418. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72419. var _this = _super.call(this, scene.getEngine(), name) || this;
  72420. // Members
  72421. /**
  72422. * The PassPostProcess id in the pipeline that contains the original scene color
  72423. */
  72424. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72425. /**
  72426. * The SSAO PostProcess id in the pipeline
  72427. */
  72428. _this.SSAORenderEffect = "SSAORenderEffect";
  72429. /**
  72430. * The horizontal blur PostProcess id in the pipeline
  72431. */
  72432. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72433. /**
  72434. * The vertical blur PostProcess id in the pipeline
  72435. */
  72436. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72437. /**
  72438. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72439. */
  72440. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72441. /**
  72442. * The output strength of the SSAO post-process. Default value is 1.0.
  72443. */
  72444. _this.totalStrength = 1.0;
  72445. /**
  72446. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72447. */
  72448. _this.maxZ = 100.0;
  72449. /**
  72450. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72451. */
  72452. _this.minZAspect = 0.2;
  72453. /**
  72454. * Number of samples used for the SSAO calculations. Default value is 8
  72455. */
  72456. _this._samples = 8;
  72457. /**
  72458. * Are we using bilateral blur ?
  72459. */
  72460. _this._expensiveBlur = true;
  72461. /**
  72462. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72463. */
  72464. _this.radius = 2.0;
  72465. /**
  72466. * The base color of the SSAO post-process
  72467. * The final result is "base + ssao" between [0, 1]
  72468. */
  72469. _this.base = 0.1;
  72470. _this._firstUpdate = true;
  72471. _this._scene = scene;
  72472. if (!_this.isSupported) {
  72473. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72474. return _this;
  72475. }
  72476. var ssaoRatio = ratio.ssaoRatio || ratio;
  72477. var blurRatio = ratio.blurRatio || ratio;
  72478. // Set up assets
  72479. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72480. _this._createRandomTexture();
  72481. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72482. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72483. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72484. _this._createSSAOPostProcess(1.0);
  72485. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72486. _this._createSSAOCombinePostProcess(blurRatio);
  72487. // Set up pipeline
  72488. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72489. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72490. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72491. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72492. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72493. // Finish
  72494. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72495. if (cameras)
  72496. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72497. return _this;
  72498. }
  72499. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72500. get: function () {
  72501. return this._samples;
  72502. },
  72503. set: function (n) {
  72504. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72505. this._samples = n;
  72506. this._sampleSphere = this._generateHemisphere();
  72507. this._firstUpdate = true;
  72508. },
  72509. enumerable: true,
  72510. configurable: true
  72511. });
  72512. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72513. get: function () {
  72514. return this._expensiveBlur;
  72515. },
  72516. set: function (b) {
  72517. 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"]);
  72518. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72519. this._expensiveBlur = b;
  72520. this._firstUpdate = true;
  72521. },
  72522. enumerable: true,
  72523. configurable: true
  72524. });
  72525. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72526. /**
  72527. * Support test.
  72528. */
  72529. get: function () {
  72530. var engine = BABYLON.Engine.LastCreatedEngine;
  72531. if (!engine) {
  72532. return false;
  72533. }
  72534. return engine.getCaps().drawBuffersExtension;
  72535. },
  72536. enumerable: true,
  72537. configurable: true
  72538. });
  72539. // Public Methods
  72540. /**
  72541. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72542. */
  72543. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72544. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72545. for (var i = 0; i < this._scene.cameras.length; i++) {
  72546. var camera = this._scene.cameras[i];
  72547. this._originalColorPostProcess.dispose(camera);
  72548. this._ssaoPostProcess.dispose(camera);
  72549. this._blurHPostProcess.dispose(camera);
  72550. this._blurVPostProcess.dispose(camera);
  72551. this._ssaoCombinePostProcess.dispose(camera);
  72552. }
  72553. this._randomTexture.dispose();
  72554. if (disableGeometryBufferRenderer)
  72555. this._scene.disableGeometryBufferRenderer();
  72556. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72557. _super.prototype.dispose.call(this);
  72558. };
  72559. // Private Methods
  72560. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72561. var _this = this;
  72562. this._samplerOffsets = [];
  72563. var expensive = this.expensiveBlur;
  72564. for (var i = -8; i < 8; i++) {
  72565. this._samplerOffsets.push(i * 2 + 0.5);
  72566. }
  72567. 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");
  72568. this._blurHPostProcess.onApply = function (effect) {
  72569. if (!_this._scene.activeCamera) {
  72570. return;
  72571. }
  72572. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72573. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72574. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72575. effect.setFloat("radius", _this.radius);
  72576. effect.setTexture("depthSampler", _this._depthTexture);
  72577. if (_this._firstUpdate) {
  72578. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72579. }
  72580. };
  72581. 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");
  72582. this._blurVPostProcess.onApply = function (effect) {
  72583. if (!_this._scene.activeCamera) {
  72584. return;
  72585. }
  72586. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72587. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72588. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72589. effect.setFloat("radius", _this.radius);
  72590. effect.setTexture("depthSampler", _this._depthTexture);
  72591. if (_this._firstUpdate) {
  72592. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72593. _this._firstUpdate = false;
  72594. }
  72595. };
  72596. };
  72597. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72598. this._firstUpdate = true;
  72599. _super.prototype._rebuild.call(this);
  72600. };
  72601. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72602. var numSamples = this.samples;
  72603. var result = [];
  72604. var vector, scale;
  72605. var rand = function (min, max) {
  72606. return Math.random() * (max - min) + min;
  72607. };
  72608. var i = 0;
  72609. while (i < numSamples) {
  72610. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72611. vector.normalize();
  72612. scale = i / numSamples;
  72613. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72614. vector.scaleInPlace(scale);
  72615. result.push(vector.x, vector.y, vector.z);
  72616. i++;
  72617. }
  72618. return result;
  72619. };
  72620. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72621. var _this = this;
  72622. var numSamples = this.samples;
  72623. this._sampleSphere = this._generateHemisphere();
  72624. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72625. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72626. "base", "range", "projection", "near", "far", "texelSize",
  72627. "xViewport", "yViewport", "maxZ", "minZAspect"
  72628. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72629. this._ssaoPostProcess.onApply = function (effect) {
  72630. if (_this._firstUpdate) {
  72631. effect.setArray3("sampleSphere", _this._sampleSphere);
  72632. effect.setFloat("randTextureTiles", 4.0);
  72633. }
  72634. if (!_this._scene.activeCamera) {
  72635. return;
  72636. }
  72637. effect.setFloat("samplesFactor", 1 / _this.samples);
  72638. effect.setFloat("totalStrength", _this.totalStrength);
  72639. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72640. effect.setFloat("radius", _this.radius);
  72641. effect.setFloat("maxZ", _this.maxZ);
  72642. effect.setFloat("minZAspect", _this.minZAspect);
  72643. effect.setFloat("base", _this.base);
  72644. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72645. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72646. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72647. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72648. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72649. effect.setTexture("textureSampler", _this._depthTexture);
  72650. effect.setTexture("normalSampler", _this._normalTexture);
  72651. effect.setTexture("randomSampler", _this._randomTexture);
  72652. };
  72653. };
  72654. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72655. var _this = this;
  72656. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72657. this._ssaoCombinePostProcess.onApply = function (effect) {
  72658. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72659. };
  72660. };
  72661. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72662. var size = 512;
  72663. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72664. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72665. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72666. var context = this._randomTexture.getContext();
  72667. var rand = function (min, max) {
  72668. return Math.random() * (max - min) + min;
  72669. };
  72670. var randVector = BABYLON.Vector3.Zero();
  72671. for (var x = 0; x < size; x++) {
  72672. for (var y = 0; y < size; y++) {
  72673. randVector.x = rand(0.0, 1.0);
  72674. randVector.y = rand(0.0, 1.0);
  72675. randVector.z = 0.0;
  72676. randVector.normalize();
  72677. randVector.scaleInPlace(255);
  72678. randVector.x = Math.floor(randVector.x);
  72679. randVector.y = Math.floor(randVector.y);
  72680. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72681. context.fillRect(x, y, 1, 1);
  72682. }
  72683. }
  72684. this._randomTexture.update(false);
  72685. };
  72686. __decorate([
  72687. BABYLON.serialize()
  72688. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72689. __decorate([
  72690. BABYLON.serialize()
  72691. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72692. __decorate([
  72693. BABYLON.serialize()
  72694. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72695. __decorate([
  72696. BABYLON.serialize("samples")
  72697. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72698. __decorate([
  72699. BABYLON.serialize("expensiveBlur")
  72700. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72701. __decorate([
  72702. BABYLON.serialize()
  72703. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72704. __decorate([
  72705. BABYLON.serialize()
  72706. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72707. return SSAO2RenderingPipeline;
  72708. }(BABYLON.PostProcessRenderPipeline));
  72709. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72710. })(BABYLON || (BABYLON = {}));
  72711. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72712. // BABYLON.JS Chromatic Aberration GLSL Shader
  72713. // Author: Olivier Guyot
  72714. // Separates very slightly R, G and B colors on the edges of the screen
  72715. // Inspired by Francois Tarlier & Martins Upitis
  72716. var BABYLON;
  72717. (function (BABYLON) {
  72718. var LensRenderingPipeline = /** @class */ (function (_super) {
  72719. __extends(LensRenderingPipeline, _super);
  72720. /**
  72721. * @constructor
  72722. *
  72723. * Effect parameters are as follow:
  72724. * {
  72725. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72726. * edge_blur: number; // from 0 to x (1 for realism)
  72727. * distortion: number; // from 0 to x (1 for realism)
  72728. * grain_amount: number; // from 0 to 1
  72729. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72730. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72731. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72732. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72733. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72734. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72735. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72736. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72737. * }
  72738. * Note: if an effect parameter is unset, effect is disabled
  72739. *
  72740. * @param {string} name - The rendering pipeline name
  72741. * @param {object} parameters - An object containing all parameters (see above)
  72742. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72743. * @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)
  72744. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72745. */
  72746. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72747. if (ratio === void 0) { ratio = 1.0; }
  72748. var _this = _super.call(this, scene.getEngine(), name) || this;
  72749. // Lens effects can be of the following:
  72750. // - chromatic aberration (slight shift of RGB colors)
  72751. // - blur on the edge of the lens
  72752. // - lens distortion
  72753. // - depth-of-field blur & highlights enhancing
  72754. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72755. // - grain effect (noise or custom texture)
  72756. // Two additional texture samplers are needed:
  72757. // - depth map (for depth-of-field)
  72758. // - grain texture
  72759. /**
  72760. * The chromatic aberration PostProcess id in the pipeline
  72761. */
  72762. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72763. /**
  72764. * The highlights enhancing PostProcess id in the pipeline
  72765. */
  72766. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72767. /**
  72768. * The depth-of-field PostProcess id in the pipeline
  72769. */
  72770. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72771. _this._scene = scene;
  72772. // Fetch texture samplers
  72773. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72774. if (parameters.grain_texture) {
  72775. _this._grainTexture = parameters.grain_texture;
  72776. }
  72777. else {
  72778. _this._createGrainTexture();
  72779. }
  72780. // save parameters
  72781. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72782. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72783. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72784. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72785. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72786. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72787. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72788. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72789. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72790. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72791. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72792. // Create effects
  72793. _this._createChromaticAberrationPostProcess(ratio);
  72794. _this._createHighlightsPostProcess(ratio);
  72795. _this._createDepthOfFieldPostProcess(ratio / 4);
  72796. // Set up pipeline
  72797. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72798. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72799. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72800. if (_this._highlightsGain === -1) {
  72801. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72802. }
  72803. // Finish
  72804. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72805. if (cameras) {
  72806. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72807. }
  72808. return _this;
  72809. }
  72810. // public methods (self explanatory)
  72811. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72812. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72813. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72814. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72815. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72816. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72817. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72818. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72819. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72820. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72821. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72822. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72823. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72824. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72825. };
  72826. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72827. this._highlightsPostProcess.updateEffect();
  72828. };
  72829. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72830. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72831. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72832. this._highlightsGain = amount;
  72833. };
  72834. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72835. if (this._highlightsGain === -1) {
  72836. this._highlightsGain = 1.0;
  72837. }
  72838. this._highlightsThreshold = amount;
  72839. };
  72840. LensRenderingPipeline.prototype.disableHighlights = function () {
  72841. this._highlightsGain = -1;
  72842. };
  72843. /**
  72844. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72845. */
  72846. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72847. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72848. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72849. this._chromaticAberrationPostProcess = null;
  72850. this._highlightsPostProcess = null;
  72851. this._depthOfFieldPostProcess = null;
  72852. this._grainTexture.dispose();
  72853. if (disableDepthRender)
  72854. this._scene.disableDepthRenderer();
  72855. };
  72856. // colors shifting and distortion
  72857. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72858. var _this = this;
  72859. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72860. [], // samplers
  72861. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72862. this._chromaticAberrationPostProcess.onApply = function (effect) {
  72863. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  72864. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72865. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72866. effect.setFloat('radialIntensity', 1);
  72867. effect.setFloat2('direction', 17, 17);
  72868. effect.setFloat2('centerPosition', 0.5, 0.5);
  72869. };
  72870. };
  72871. // highlights enhancing
  72872. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  72873. var _this = this;
  72874. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  72875. [], // samplers
  72876. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  72877. this._highlightsPostProcess.onApply = function (effect) {
  72878. effect.setFloat('gain', _this._highlightsGain);
  72879. effect.setFloat('threshold', _this._highlightsThreshold);
  72880. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  72881. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72882. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72883. };
  72884. };
  72885. // colors shifting and distortion
  72886. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  72887. var _this = this;
  72888. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  72889. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  72890. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  72891. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72892. this._depthOfFieldPostProcess.onApply = function (effect) {
  72893. effect.setTexture("depthSampler", _this._depthTexture);
  72894. effect.setTexture("grainSampler", _this._grainTexture);
  72895. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  72896. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  72897. effect.setFloat('grain_amount', _this._grainAmount);
  72898. effect.setBool('blur_noise', _this._blurNoise);
  72899. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  72900. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  72901. effect.setFloat('distortion', _this._distortion);
  72902. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  72903. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  72904. effect.setFloat('aperture', _this._dofAperture);
  72905. effect.setFloat('darken', _this._dofDarken);
  72906. effect.setFloat('edge_blur', _this._edgeBlur);
  72907. effect.setBool('highlights', (_this._highlightsGain !== -1));
  72908. if (_this._scene.activeCamera) {
  72909. effect.setFloat('near', _this._scene.activeCamera.minZ);
  72910. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  72911. }
  72912. };
  72913. };
  72914. // creates a black and white random noise texture, 512x512
  72915. LensRenderingPipeline.prototype._createGrainTexture = function () {
  72916. var size = 512;
  72917. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72918. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72919. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72920. var context = this._grainTexture.getContext();
  72921. var rand = function (min, max) {
  72922. return Math.random() * (max - min) + min;
  72923. };
  72924. var value;
  72925. for (var x = 0; x < size; x++) {
  72926. for (var y = 0; y < size; y++) {
  72927. value = Math.floor(rand(0.42, 0.58) * 255);
  72928. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  72929. context.fillRect(x, y, 1, 1);
  72930. }
  72931. }
  72932. this._grainTexture.update(false);
  72933. };
  72934. return LensRenderingPipeline;
  72935. }(BABYLON.PostProcessRenderPipeline));
  72936. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  72937. })(BABYLON || (BABYLON = {}));
  72938. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  72939. var BABYLON;
  72940. (function (BABYLON) {
  72941. var StandardRenderingPipeline = /** @class */ (function (_super) {
  72942. __extends(StandardRenderingPipeline, _super);
  72943. /**
  72944. * @constructor
  72945. * @param {string} name - The rendering pipeline name
  72946. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72947. * @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)
  72948. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  72949. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72950. */
  72951. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  72952. if (originalPostProcess === void 0) { originalPostProcess = null; }
  72953. var _this = _super.call(this, scene.getEngine(), name) || this;
  72954. _this.downSampleX4PostProcess = null;
  72955. _this.brightPassPostProcess = null;
  72956. _this.blurHPostProcesses = [];
  72957. _this.blurVPostProcesses = [];
  72958. _this.textureAdderPostProcess = null;
  72959. _this.volumetricLightPostProcess = null;
  72960. _this.volumetricLightSmoothXPostProcess = null;
  72961. _this.volumetricLightSmoothYPostProcess = null;
  72962. _this.volumetricLightMergePostProces = null;
  72963. _this.volumetricLightFinalPostProcess = null;
  72964. _this.luminancePostProcess = null;
  72965. _this.luminanceDownSamplePostProcesses = [];
  72966. _this.hdrPostProcess = null;
  72967. _this.textureAdderFinalPostProcess = null;
  72968. _this.lensFlareFinalPostProcess = null;
  72969. _this.hdrFinalPostProcess = null;
  72970. _this.lensFlarePostProcess = null;
  72971. _this.lensFlareComposePostProcess = null;
  72972. _this.motionBlurPostProcess = null;
  72973. _this.depthOfFieldPostProcess = null;
  72974. // Values
  72975. _this.brightThreshold = 1.0;
  72976. _this.blurWidth = 512.0;
  72977. _this.horizontalBlur = false;
  72978. _this.exposure = 1.0;
  72979. _this.lensTexture = null;
  72980. _this.volumetricLightCoefficient = 0.2;
  72981. _this.volumetricLightPower = 4.0;
  72982. _this.volumetricLightBlurScale = 64.0;
  72983. _this.sourceLight = null;
  72984. _this.hdrMinimumLuminance = 1.0;
  72985. _this.hdrDecreaseRate = 0.5;
  72986. _this.hdrIncreaseRate = 0.5;
  72987. _this.lensColorTexture = null;
  72988. _this.lensFlareStrength = 20.0;
  72989. _this.lensFlareGhostDispersal = 1.4;
  72990. _this.lensFlareHaloWidth = 0.7;
  72991. _this.lensFlareDistortionStrength = 16.0;
  72992. _this.lensStarTexture = null;
  72993. _this.lensFlareDirtTexture = null;
  72994. _this.depthOfFieldDistance = 10.0;
  72995. _this.depthOfFieldBlurWidth = 64.0;
  72996. _this.motionStrength = 1.0;
  72997. // IAnimatable
  72998. _this.animations = [];
  72999. _this._currentDepthOfFieldSource = null;
  73000. _this._hdrCurrentLuminance = 1.0;
  73001. // Getters and setters
  73002. _this._bloomEnabled = true;
  73003. _this._depthOfFieldEnabled = false;
  73004. _this._vlsEnabled = false;
  73005. _this._lensFlareEnabled = false;
  73006. _this._hdrEnabled = false;
  73007. _this._motionBlurEnabled = false;
  73008. _this._motionBlurSamples = 64.0;
  73009. _this._volumetricLightStepsCount = 50.0;
  73010. _this._cameras = cameras || [];
  73011. // Initialize
  73012. _this._scene = scene;
  73013. _this._basePostProcess = originalPostProcess;
  73014. _this._ratio = ratio;
  73015. // Misc
  73016. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73017. // Finish
  73018. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73019. _this._buildPipeline();
  73020. return _this;
  73021. }
  73022. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73023. get: function () {
  73024. return this._bloomEnabled;
  73025. },
  73026. set: function (enabled) {
  73027. if (this._bloomEnabled === enabled) {
  73028. return;
  73029. }
  73030. this._bloomEnabled = enabled;
  73031. this._buildPipeline();
  73032. },
  73033. enumerable: true,
  73034. configurable: true
  73035. });
  73036. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73037. get: function () {
  73038. return this._depthOfFieldEnabled;
  73039. },
  73040. set: function (enabled) {
  73041. if (this._depthOfFieldEnabled === enabled) {
  73042. return;
  73043. }
  73044. this._depthOfFieldEnabled = enabled;
  73045. this._buildPipeline();
  73046. },
  73047. enumerable: true,
  73048. configurable: true
  73049. });
  73050. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73051. get: function () {
  73052. return this._lensFlareEnabled;
  73053. },
  73054. set: function (enabled) {
  73055. if (this._lensFlareEnabled === enabled) {
  73056. return;
  73057. }
  73058. this._lensFlareEnabled = enabled;
  73059. this._buildPipeline();
  73060. },
  73061. enumerable: true,
  73062. configurable: true
  73063. });
  73064. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73065. get: function () {
  73066. return this._hdrEnabled;
  73067. },
  73068. set: function (enabled) {
  73069. if (this._hdrEnabled === enabled) {
  73070. return;
  73071. }
  73072. this._hdrEnabled = enabled;
  73073. this._buildPipeline();
  73074. },
  73075. enumerable: true,
  73076. configurable: true
  73077. });
  73078. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73079. get: function () {
  73080. return this._vlsEnabled;
  73081. },
  73082. set: function (enabled) {
  73083. if (this._vlsEnabled === enabled) {
  73084. return;
  73085. }
  73086. if (enabled) {
  73087. var geometry = this._scene.enableGeometryBufferRenderer();
  73088. if (!geometry) {
  73089. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73090. return;
  73091. }
  73092. }
  73093. this._vlsEnabled = enabled;
  73094. this._buildPipeline();
  73095. },
  73096. enumerable: true,
  73097. configurable: true
  73098. });
  73099. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73100. get: function () {
  73101. return this._motionBlurEnabled;
  73102. },
  73103. set: function (enabled) {
  73104. if (this._motionBlurEnabled === enabled) {
  73105. return;
  73106. }
  73107. this._motionBlurEnabled = enabled;
  73108. this._buildPipeline();
  73109. },
  73110. enumerable: true,
  73111. configurable: true
  73112. });
  73113. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73114. get: function () {
  73115. return this._volumetricLightStepsCount;
  73116. },
  73117. set: function (count) {
  73118. if (this.volumetricLightPostProcess) {
  73119. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73120. }
  73121. this._volumetricLightStepsCount = count;
  73122. },
  73123. enumerable: true,
  73124. configurable: true
  73125. });
  73126. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73127. get: function () {
  73128. return this._motionBlurSamples;
  73129. },
  73130. set: function (samples) {
  73131. if (this.motionBlurPostProcess) {
  73132. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73133. }
  73134. this._motionBlurSamples = samples;
  73135. },
  73136. enumerable: true,
  73137. configurable: true
  73138. });
  73139. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73140. var _this = this;
  73141. var ratio = this._ratio;
  73142. var scene = this._scene;
  73143. this._disposePostProcesses();
  73144. this._reset();
  73145. // Create pass post-process
  73146. if (!this._basePostProcess) {
  73147. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73148. this.originalPostProcess.onApply = function (effect) {
  73149. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73150. };
  73151. }
  73152. else {
  73153. this.originalPostProcess = this._basePostProcess;
  73154. }
  73155. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73156. this._currentDepthOfFieldSource = this.originalPostProcess;
  73157. if (this._vlsEnabled) {
  73158. // Create volumetric light
  73159. this._createVolumetricLightPostProcess(scene, ratio);
  73160. // Create volumetric light final post-process
  73161. 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);
  73162. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73163. }
  73164. if (this._bloomEnabled) {
  73165. // Create down sample X4 post-process
  73166. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73167. // Create bright pass post-process
  73168. this._createBrightPassPostProcess(scene, ratio / 2);
  73169. // Create gaussian blur post-processes (down sampling blurs)
  73170. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73171. // Create texture adder post-process
  73172. this._createTextureAdderPostProcess(scene, ratio);
  73173. // Create depth-of-field source post-process
  73174. 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);
  73175. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73176. }
  73177. if (this._lensFlareEnabled) {
  73178. // Create lens flare post-process
  73179. this._createLensFlarePostProcess(scene, ratio);
  73180. // Create depth-of-field source post-process post lens-flare and disable it now
  73181. 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);
  73182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73183. }
  73184. if (this._hdrEnabled) {
  73185. // Create luminance
  73186. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73187. // Create HDR
  73188. this._createHdrPostProcess(scene, ratio);
  73189. // Create depth-of-field source post-process post hdr and disable it now
  73190. 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);
  73191. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73192. }
  73193. if (this._depthOfFieldEnabled) {
  73194. // Create gaussian blur used by depth-of-field
  73195. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73196. // Create depth-of-field post-process
  73197. this._createDepthOfFieldPostProcess(scene, ratio);
  73198. }
  73199. if (this._motionBlurEnabled) {
  73200. // Create motion blur post-process
  73201. this._createMotionBlurPostProcess(scene, ratio);
  73202. }
  73203. if (this._cameras !== null) {
  73204. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73205. }
  73206. };
  73207. // Down Sample X4 Post-Processs
  73208. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73209. var _this = this;
  73210. var downSampleX4Offsets = new Array(32);
  73211. 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);
  73212. this.downSampleX4PostProcess.onApply = function (effect) {
  73213. var id = 0;
  73214. var width = _this.downSampleX4PostProcess.width;
  73215. var height = _this.downSampleX4PostProcess.height;
  73216. for (var i = -2; i < 2; i++) {
  73217. for (var j = -2; j < 2; j++) {
  73218. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73219. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73220. id += 2;
  73221. }
  73222. }
  73223. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73224. };
  73225. // Add to pipeline
  73226. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73227. };
  73228. // Brightpass Post-Process
  73229. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73230. var _this = this;
  73231. var brightOffsets = new Array(8);
  73232. 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);
  73233. this.brightPassPostProcess.onApply = function (effect) {
  73234. var sU = (1.0 / _this.brightPassPostProcess.width);
  73235. var sV = (1.0 / _this.brightPassPostProcess.height);
  73236. brightOffsets[0] = -0.5 * sU;
  73237. brightOffsets[1] = 0.5 * sV;
  73238. brightOffsets[2] = 0.5 * sU;
  73239. brightOffsets[3] = 0.5 * sV;
  73240. brightOffsets[4] = -0.5 * sU;
  73241. brightOffsets[5] = -0.5 * sV;
  73242. brightOffsets[6] = 0.5 * sU;
  73243. brightOffsets[7] = -0.5 * sV;
  73244. effect.setArray2("dsOffsets", brightOffsets);
  73245. effect.setFloat("brightThreshold", _this.brightThreshold);
  73246. };
  73247. // Add to pipeline
  73248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73249. };
  73250. // Create blur H&V post-processes
  73251. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73252. var _this = this;
  73253. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73254. var engine = scene.getEngine();
  73255. 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);
  73256. 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);
  73257. blurX.onActivateObservable.add(function () {
  73258. var dw = blurX.width / engine.getRenderWidth();
  73259. blurX.kernel = _this[blurWidthKey] * dw;
  73260. });
  73261. blurY.onActivateObservable.add(function () {
  73262. var dw = blurY.height / engine.getRenderHeight();
  73263. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73264. });
  73265. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73267. this.blurHPostProcesses.push(blurX);
  73268. this.blurVPostProcesses.push(blurY);
  73269. };
  73270. // Create texture adder post-process
  73271. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73272. var _this = this;
  73273. 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);
  73274. this.textureAdderPostProcess.onApply = function (effect) {
  73275. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73276. effect.setTexture("lensSampler", _this.lensTexture);
  73277. effect.setFloat("exposure", _this.exposure);
  73278. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73279. };
  73280. // Add to pipeline
  73281. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73282. };
  73283. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73284. var _this = this;
  73285. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73286. geometryRenderer.enablePosition = true;
  73287. var geometry = geometryRenderer.getGBuffer();
  73288. // Base post-process
  73289. 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));
  73290. var depthValues = BABYLON.Vector2.Zero();
  73291. this.volumetricLightPostProcess.onApply = function (effect) {
  73292. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73293. var generator = _this.sourceLight.getShadowGenerator();
  73294. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73295. effect.setTexture("positionSampler", geometry.textures[2]);
  73296. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73297. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73298. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73299. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73300. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73301. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73302. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73303. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73304. effect.setVector2("depthValues", depthValues);
  73305. }
  73306. };
  73307. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73308. // Smooth
  73309. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73310. // Merge
  73311. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73312. this.volumetricLightMergePostProces.onApply = function (effect) {
  73313. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73314. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73315. };
  73316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73317. };
  73318. // Create luminance
  73319. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73320. var _this = this;
  73321. // Create luminance
  73322. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73323. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73324. var offsets = [];
  73325. this.luminancePostProcess.onApply = function (effect) {
  73326. var sU = (1.0 / _this.luminancePostProcess.width);
  73327. var sV = (1.0 / _this.luminancePostProcess.height);
  73328. offsets[0] = -0.5 * sU;
  73329. offsets[1] = 0.5 * sV;
  73330. offsets[2] = 0.5 * sU;
  73331. offsets[3] = 0.5 * sV;
  73332. offsets[4] = -0.5 * sU;
  73333. offsets[5] = -0.5 * sV;
  73334. offsets[6] = 0.5 * sU;
  73335. offsets[7] = -0.5 * sV;
  73336. effect.setArray2("lumOffsets", offsets);
  73337. };
  73338. // Add to pipeline
  73339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73340. // Create down sample luminance
  73341. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73342. var size = Math.pow(3, i);
  73343. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73344. if (i === 0) {
  73345. defines += "#define FINAL_DOWN_SAMPLER";
  73346. }
  73347. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73348. this.luminanceDownSamplePostProcesses.push(postProcess);
  73349. }
  73350. // Create callbacks and add effects
  73351. var lastLuminance = this.luminancePostProcess;
  73352. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73353. var downSampleOffsets = new Array(18);
  73354. pp.onApply = function (effect) {
  73355. if (!lastLuminance) {
  73356. return;
  73357. }
  73358. var id = 0;
  73359. for (var x = -1; x < 2; x++) {
  73360. for (var y = -1; y < 2; y++) {
  73361. downSampleOffsets[id] = x / lastLuminance.width;
  73362. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73363. id += 2;
  73364. }
  73365. }
  73366. effect.setArray2("dsOffsets", downSampleOffsets);
  73367. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73368. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73369. lastLuminance = _this.luminancePostProcess;
  73370. }
  73371. else {
  73372. lastLuminance = pp;
  73373. }
  73374. };
  73375. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73376. pp.onAfterRender = function (effect) {
  73377. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73378. 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);
  73379. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73380. };
  73381. }
  73382. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73383. });
  73384. };
  73385. // Create HDR post-process
  73386. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73387. var _this = this;
  73388. 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);
  73389. var outputLiminance = 1;
  73390. var time = 0;
  73391. var lastTime = 0;
  73392. this.hdrPostProcess.onApply = function (effect) {
  73393. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73394. time += scene.getEngine().getDeltaTime();
  73395. if (outputLiminance < 0) {
  73396. outputLiminance = _this._hdrCurrentLuminance;
  73397. }
  73398. else {
  73399. var dt = (lastTime - time) / 1000.0;
  73400. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73401. outputLiminance += _this.hdrDecreaseRate * dt;
  73402. }
  73403. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73404. outputLiminance -= _this.hdrIncreaseRate * dt;
  73405. }
  73406. else {
  73407. outputLiminance = _this._hdrCurrentLuminance;
  73408. }
  73409. }
  73410. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73411. effect.setFloat("averageLuminance", outputLiminance);
  73412. lastTime = time;
  73413. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73414. };
  73415. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73416. };
  73417. // Create lens flare post-process
  73418. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73419. var _this = this;
  73420. 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);
  73421. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73422. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73423. 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);
  73424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73425. var resolution = new BABYLON.Vector2(0, 0);
  73426. // Lens flare
  73427. this.lensFlarePostProcess.onApply = function (effect) {
  73428. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73429. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73430. effect.setFloat("strength", _this.lensFlareStrength);
  73431. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73432. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73433. // Shift
  73434. resolution.x = _this.lensFlarePostProcess.width;
  73435. resolution.y = _this.lensFlarePostProcess.height;
  73436. effect.setVector2("resolution", resolution);
  73437. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73438. };
  73439. // Compose
  73440. 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);
  73441. 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);
  73442. this.lensFlareComposePostProcess.onApply = function (effect) {
  73443. if (!_this._scene.activeCamera) {
  73444. return;
  73445. }
  73446. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73447. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73448. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73449. // Lens start rotation matrix
  73450. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73451. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73452. 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));
  73453. camRot *= 4.0;
  73454. 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);
  73455. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73456. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73457. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73458. };
  73459. };
  73460. // Create depth-of-field post-process
  73461. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73462. var _this = this;
  73463. 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);
  73464. this.depthOfFieldPostProcess.onApply = function (effect) {
  73465. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73466. effect.setTexture("depthSampler", _this._getDepthTexture());
  73467. effect.setFloat("distance", _this.depthOfFieldDistance);
  73468. };
  73469. // Add to pipeline
  73470. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73471. };
  73472. // Create motion blur post-process
  73473. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73474. var _this = this;
  73475. 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);
  73476. var motionScale = 0;
  73477. var prevViewProjection = BABYLON.Matrix.Identity();
  73478. var invViewProjection = BABYLON.Matrix.Identity();
  73479. var viewProjection = BABYLON.Matrix.Identity();
  73480. var screenSize = BABYLON.Vector2.Zero();
  73481. this.motionBlurPostProcess.onApply = function (effect) {
  73482. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73483. viewProjection.invertToRef(invViewProjection);
  73484. effect.setMatrix("inverseViewProjection", invViewProjection);
  73485. effect.setMatrix("prevViewProjection", prevViewProjection);
  73486. prevViewProjection = viewProjection;
  73487. screenSize.x = _this.motionBlurPostProcess.width;
  73488. screenSize.y = _this.motionBlurPostProcess.height;
  73489. effect.setVector2("screenSize", screenSize);
  73490. motionScale = scene.getEngine().getFps() / 60.0;
  73491. effect.setFloat("motionScale", motionScale);
  73492. effect.setFloat("motionStrength", _this.motionStrength);
  73493. effect.setTexture("depthSampler", _this._getDepthTexture());
  73494. };
  73495. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73496. };
  73497. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73498. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73499. var renderer = this._scene.enableGeometryBufferRenderer();
  73500. return renderer.getGBuffer().textures[0];
  73501. }
  73502. return this._scene.enableDepthRenderer().getDepthMap();
  73503. };
  73504. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73505. for (var i = 0; i < this._cameras.length; i++) {
  73506. var camera = this._cameras[i];
  73507. if (this.originalPostProcess) {
  73508. this.originalPostProcess.dispose(camera);
  73509. }
  73510. if (this.downSampleX4PostProcess) {
  73511. this.downSampleX4PostProcess.dispose(camera);
  73512. }
  73513. if (this.brightPassPostProcess) {
  73514. this.brightPassPostProcess.dispose(camera);
  73515. }
  73516. if (this.textureAdderPostProcess) {
  73517. this.textureAdderPostProcess.dispose(camera);
  73518. }
  73519. if (this.textureAdderFinalPostProcess) {
  73520. this.textureAdderFinalPostProcess.dispose(camera);
  73521. }
  73522. if (this.volumetricLightPostProcess) {
  73523. this.volumetricLightPostProcess.dispose(camera);
  73524. }
  73525. if (this.volumetricLightSmoothXPostProcess) {
  73526. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73527. }
  73528. if (this.volumetricLightSmoothYPostProcess) {
  73529. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73530. }
  73531. if (this.volumetricLightMergePostProces) {
  73532. this.volumetricLightMergePostProces.dispose(camera);
  73533. }
  73534. if (this.volumetricLightFinalPostProcess) {
  73535. this.volumetricLightFinalPostProcess.dispose(camera);
  73536. }
  73537. if (this.lensFlarePostProcess) {
  73538. this.lensFlarePostProcess.dispose(camera);
  73539. }
  73540. if (this.lensFlareComposePostProcess) {
  73541. this.lensFlareComposePostProcess.dispose(camera);
  73542. }
  73543. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73544. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73545. }
  73546. if (this.luminancePostProcess) {
  73547. this.luminancePostProcess.dispose(camera);
  73548. }
  73549. if (this.hdrPostProcess) {
  73550. this.hdrPostProcess.dispose(camera);
  73551. }
  73552. if (this.hdrFinalPostProcess) {
  73553. this.hdrFinalPostProcess.dispose(camera);
  73554. }
  73555. if (this.depthOfFieldPostProcess) {
  73556. this.depthOfFieldPostProcess.dispose(camera);
  73557. }
  73558. if (this.motionBlurPostProcess) {
  73559. this.motionBlurPostProcess.dispose(camera);
  73560. }
  73561. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73562. this.blurHPostProcesses[j].dispose(camera);
  73563. }
  73564. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73565. this.blurVPostProcesses[j].dispose(camera);
  73566. }
  73567. }
  73568. this.originalPostProcess = null;
  73569. this.downSampleX4PostProcess = null;
  73570. this.brightPassPostProcess = null;
  73571. this.textureAdderPostProcess = null;
  73572. this.textureAdderFinalPostProcess = null;
  73573. this.volumetricLightPostProcess = null;
  73574. this.volumetricLightSmoothXPostProcess = null;
  73575. this.volumetricLightSmoothYPostProcess = null;
  73576. this.volumetricLightMergePostProces = null;
  73577. this.volumetricLightFinalPostProcess = null;
  73578. this.lensFlarePostProcess = null;
  73579. this.lensFlareComposePostProcess = null;
  73580. this.luminancePostProcess = null;
  73581. this.hdrPostProcess = null;
  73582. this.hdrFinalPostProcess = null;
  73583. this.depthOfFieldPostProcess = null;
  73584. this.motionBlurPostProcess = null;
  73585. this.luminanceDownSamplePostProcesses = [];
  73586. this.blurHPostProcesses = [];
  73587. this.blurVPostProcesses = [];
  73588. };
  73589. // Dispose
  73590. StandardRenderingPipeline.prototype.dispose = function () {
  73591. this._disposePostProcesses();
  73592. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73593. _super.prototype.dispose.call(this);
  73594. };
  73595. // Serialize rendering pipeline
  73596. StandardRenderingPipeline.prototype.serialize = function () {
  73597. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73598. serializationObject.customType = "StandardRenderingPipeline";
  73599. return serializationObject;
  73600. };
  73601. /**
  73602. * Static members
  73603. */
  73604. // Parse serialized pipeline
  73605. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73606. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73607. };
  73608. // Luminance steps
  73609. StandardRenderingPipeline.LuminanceSteps = 6;
  73610. __decorate([
  73611. BABYLON.serialize()
  73612. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73613. __decorate([
  73614. BABYLON.serialize()
  73615. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73616. __decorate([
  73617. BABYLON.serialize()
  73618. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73619. __decorate([
  73620. BABYLON.serialize()
  73621. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73622. __decorate([
  73623. BABYLON.serializeAsTexture("lensTexture")
  73624. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73625. __decorate([
  73626. BABYLON.serialize()
  73627. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73628. __decorate([
  73629. BABYLON.serialize()
  73630. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73631. __decorate([
  73632. BABYLON.serialize()
  73633. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73634. __decorate([
  73635. BABYLON.serialize()
  73636. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73637. __decorate([
  73638. BABYLON.serialize()
  73639. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73640. __decorate([
  73641. BABYLON.serialize()
  73642. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73643. __decorate([
  73644. BABYLON.serializeAsTexture("lensColorTexture")
  73645. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73646. __decorate([
  73647. BABYLON.serialize()
  73648. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73649. __decorate([
  73650. BABYLON.serialize()
  73651. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73652. __decorate([
  73653. BABYLON.serialize()
  73654. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73655. __decorate([
  73656. BABYLON.serialize()
  73657. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73658. __decorate([
  73659. BABYLON.serializeAsTexture("lensStarTexture")
  73660. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73661. __decorate([
  73662. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73663. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73664. __decorate([
  73665. BABYLON.serialize()
  73666. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73667. __decorate([
  73668. BABYLON.serialize()
  73669. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73670. __decorate([
  73671. BABYLON.serialize()
  73672. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73673. __decorate([
  73674. BABYLON.serialize()
  73675. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73676. __decorate([
  73677. BABYLON.serialize()
  73678. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73679. __decorate([
  73680. BABYLON.serialize()
  73681. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73682. __decorate([
  73683. BABYLON.serialize()
  73684. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73685. __decorate([
  73686. BABYLON.serialize()
  73687. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73688. __decorate([
  73689. BABYLON.serialize()
  73690. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73691. __decorate([
  73692. BABYLON.serialize()
  73693. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73694. __decorate([
  73695. BABYLON.serialize()
  73696. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73697. __decorate([
  73698. BABYLON.serialize()
  73699. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73700. return StandardRenderingPipeline;
  73701. }(BABYLON.PostProcessRenderPipeline));
  73702. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73703. })(BABYLON || (BABYLON = {}));
  73704. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73705. var BABYLON;
  73706. (function (BABYLON) {
  73707. var FxaaPostProcess = /** @class */ (function (_super) {
  73708. __extends(FxaaPostProcess, _super);
  73709. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73710. if (camera === void 0) { camera = null; }
  73711. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73712. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73713. _this.onApplyObservable.add(function (effect) {
  73714. var texelSize = _this.texelSize;
  73715. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73716. });
  73717. return _this;
  73718. }
  73719. return FxaaPostProcess;
  73720. }(BABYLON.PostProcess));
  73721. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73722. })(BABYLON || (BABYLON = {}));
  73723. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73724. var BABYLON;
  73725. (function (BABYLON) {
  73726. /**
  73727. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73728. */
  73729. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73730. __extends(ChromaticAberrationPostProcess, _super);
  73731. /**
  73732. * Creates a new instance ChromaticAberrationPostProcess
  73733. * @param name The name of the effect.
  73734. * @param screenWidth The width of the screen to apply the effect on.
  73735. * @param screenHeight The height of the screen to apply the effect on.
  73736. * @param options The required width/height ratio to downsize to before computing the render pass.
  73737. * @param camera The camera to apply the render pass to.
  73738. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73739. * @param engine The engine which the post process will be applied. (default: current engine)
  73740. * @param reusable If the post process can be reused on the same frame. (default: false)
  73741. * @param textureType Type of textures used when performing the post process. (default: 0)
  73742. * @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)
  73743. */
  73744. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73745. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73746. if (blockCompilation === void 0) { blockCompilation = false; }
  73747. 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;
  73748. /**
  73749. * The amount of seperation of rgb channels (default: 30)
  73750. */
  73751. _this.aberrationAmount = 30;
  73752. /**
  73753. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73754. */
  73755. _this.radialIntensity = 0;
  73756. /**
  73757. * 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))
  73758. */
  73759. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73760. /**
  73761. * 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))
  73762. */
  73763. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73764. _this.onApplyObservable.add(function (effect) {
  73765. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73766. effect.setFloat('screen_width', screenWidth);
  73767. effect.setFloat('screen_height', screenHeight);
  73768. effect.setFloat('radialIntensity', _this.radialIntensity);
  73769. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73770. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73771. });
  73772. return _this;
  73773. }
  73774. return ChromaticAberrationPostProcess;
  73775. }(BABYLON.PostProcess));
  73776. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73777. })(BABYLON || (BABYLON = {}));
  73778. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73779. var BABYLON;
  73780. (function (BABYLON) {
  73781. /**
  73782. * The GrainPostProcess adds noise to the image at mid luminance levels
  73783. */
  73784. var GrainPostProcess = /** @class */ (function (_super) {
  73785. __extends(GrainPostProcess, _super);
  73786. /**
  73787. * Creates a new instance of @see GrainPostProcess
  73788. * @param name The name of the effect.
  73789. * @param options The required width/height ratio to downsize to before computing the render pass.
  73790. * @param camera The camera to apply the render pass to.
  73791. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73792. * @param engine The engine which the post process will be applied. (default: current engine)
  73793. * @param reusable If the post process can be reused on the same frame. (default: false)
  73794. * @param textureType Type of textures used when performing the post process. (default: 0)
  73795. * @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)
  73796. */
  73797. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73798. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73799. if (blockCompilation === void 0) { blockCompilation = false; }
  73800. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73801. /**
  73802. * The intensity of the grain added (default: 30)
  73803. */
  73804. _this.intensity = 30;
  73805. /**
  73806. * If the grain should be randomized on every frame
  73807. */
  73808. _this.animated = false;
  73809. _this.onApplyObservable.add(function (effect) {
  73810. effect.setFloat('intensity', _this.intensity);
  73811. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73812. });
  73813. return _this;
  73814. }
  73815. return GrainPostProcess;
  73816. }(BABYLON.PostProcess));
  73817. BABYLON.GrainPostProcess = GrainPostProcess;
  73818. })(BABYLON || (BABYLON = {}));
  73819. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73820. var BABYLON;
  73821. (function (BABYLON) {
  73822. /**
  73823. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73824. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73825. */
  73826. var SharpenPostProcess = /** @class */ (function (_super) {
  73827. __extends(SharpenPostProcess, _super);
  73828. /**
  73829. * Creates a new instance ConvolutionPostProcess
  73830. * @param name The name of the effect.
  73831. * @param options The required width/height ratio to downsize to before computing the render pass.
  73832. * @param camera The camera to apply the render pass to.
  73833. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73834. * @param engine The engine which the post process will be applied. (default: current engine)
  73835. * @param reusable If the post process can be reused on the same frame. (default: false)
  73836. * @param textureType Type of textures used when performing the post process. (default: 0)
  73837. * @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)
  73838. */
  73839. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73840. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73841. if (blockCompilation === void 0) { blockCompilation = false; }
  73842. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73843. /**
  73844. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73845. */
  73846. _this.colorAmount = 1.0;
  73847. /**
  73848. * How much sharpness should be applied (default: 0.3)
  73849. */
  73850. _this.edgeAmount = 0.3;
  73851. _this.onApply = function (effect) {
  73852. effect.setFloat2("screenSize", _this.width, _this.height);
  73853. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73854. };
  73855. return _this;
  73856. }
  73857. return SharpenPostProcess;
  73858. }(BABYLON.PostProcess));
  73859. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73860. })(BABYLON || (BABYLON = {}));
  73861. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  73862. var BABYLON;
  73863. (function (BABYLON) {
  73864. /**
  73865. * The Blur Post Process which blurs an image based on a kernel and direction.
  73866. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  73867. */
  73868. var BlurPostProcess = /** @class */ (function (_super) {
  73869. __extends(BlurPostProcess, _super);
  73870. /**
  73871. * Creates a new instance BlurPostProcess
  73872. * @param name The name of the effect.
  73873. * @param direction The direction in which to blur the image.
  73874. * @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.
  73875. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73876. * @param camera The camera to apply the render pass to.
  73877. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73878. * @param engine The engine which the post process will be applied. (default: current engine)
  73879. * @param reusable If the post process can be reused on the same frame. (default: false)
  73880. * @param textureType Type of textures used when performing the post process. (default: 0)
  73881. * @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)
  73882. */
  73883. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  73884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  73885. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73886. if (defines === void 0) { defines = ""; }
  73887. if (blockCompilation === void 0) { blockCompilation = false; }
  73888. 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;
  73889. _this.direction = direction;
  73890. _this.blockCompilation = blockCompilation;
  73891. _this._packedFloat = false;
  73892. _this._staticDefines = "";
  73893. _this._staticDefines = defines;
  73894. _this.onApplyObservable.add(function (effect) {
  73895. if (_this._outputTexture) {
  73896. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  73897. }
  73898. else {
  73899. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  73900. }
  73901. });
  73902. _this.kernel = kernel;
  73903. return _this;
  73904. }
  73905. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  73906. /**
  73907. * Gets the length in pixels of the blur sample region
  73908. */
  73909. get: function () {
  73910. return this._idealKernel;
  73911. },
  73912. /**
  73913. * Sets the length in pixels of the blur sample region
  73914. */
  73915. set: function (v) {
  73916. if (this._idealKernel === v) {
  73917. return;
  73918. }
  73919. v = Math.max(v, 1);
  73920. this._idealKernel = v;
  73921. this._kernel = this._nearestBestKernel(v);
  73922. if (!this.blockCompilation) {
  73923. this._updateParameters();
  73924. }
  73925. },
  73926. enumerable: true,
  73927. configurable: true
  73928. });
  73929. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  73930. /**
  73931. * Gets wether or not the blur is unpacking/repacking floats
  73932. */
  73933. get: function () {
  73934. return this._packedFloat;
  73935. },
  73936. /**
  73937. * Sets wether or not the blur needs to unpack/repack floats
  73938. */
  73939. set: function (v) {
  73940. if (this._packedFloat === v) {
  73941. return;
  73942. }
  73943. this._packedFloat = v;
  73944. if (!this.blockCompilation) {
  73945. this._updateParameters();
  73946. }
  73947. },
  73948. enumerable: true,
  73949. configurable: true
  73950. });
  73951. /**
  73952. * Updates the effect with the current post process compile time values and recompiles the shader.
  73953. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  73954. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  73955. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  73956. * @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
  73957. * @param onCompiled Called when the shader has been compiled.
  73958. * @param onError Called if there is an error when compiling a shader.
  73959. */
  73960. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  73961. if (defines === void 0) { defines = null; }
  73962. if (uniforms === void 0) { uniforms = null; }
  73963. if (samplers === void 0) { samplers = null; }
  73964. this._updateParameters(onCompiled, onError);
  73965. };
  73966. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  73967. // Generate sampling offsets and weights
  73968. var N = this._kernel;
  73969. var centerIndex = (N - 1) / 2;
  73970. // Generate Gaussian sampling weights over kernel
  73971. var offsets = [];
  73972. var weights = [];
  73973. var totalWeight = 0;
  73974. for (var i = 0; i < N; i++) {
  73975. var u = i / (N - 1);
  73976. var w = this._gaussianWeight(u * 2.0 - 1);
  73977. offsets[i] = (i - centerIndex);
  73978. weights[i] = w;
  73979. totalWeight += w;
  73980. }
  73981. // Normalize weights
  73982. for (var i = 0; i < weights.length; i++) {
  73983. weights[i] /= totalWeight;
  73984. }
  73985. // Optimize: combine samples to take advantage of hardware linear sampling
  73986. // Walk from left to center, combining pairs (symmetrically)
  73987. var linearSamplingWeights = [];
  73988. var linearSamplingOffsets = [];
  73989. var linearSamplingMap = [];
  73990. for (var i = 0; i <= centerIndex; i += 2) {
  73991. var j = Math.min(i + 1, Math.floor(centerIndex));
  73992. var singleCenterSample = i === j;
  73993. if (singleCenterSample) {
  73994. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  73995. }
  73996. else {
  73997. var sharedCell = j === centerIndex;
  73998. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  73999. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74000. if (offsetLinear === 0) {
  74001. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74002. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74003. }
  74004. else {
  74005. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74006. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74007. }
  74008. }
  74009. }
  74010. for (var i = 0; i < linearSamplingMap.length; i++) {
  74011. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74012. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74013. }
  74014. // Replace with optimized
  74015. offsets = linearSamplingOffsets;
  74016. weights = linearSamplingWeights;
  74017. // Generate shaders
  74018. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74019. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74020. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74021. var defines = "";
  74022. defines += this._staticDefines;
  74023. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74024. if (this._staticDefines.indexOf("DOF") != -1) {
  74025. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74026. varyingCount--;
  74027. }
  74028. for (var i = 0; i < varyingCount; i++) {
  74029. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74030. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74031. }
  74032. var depCount = 0;
  74033. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74034. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74035. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74036. depCount++;
  74037. }
  74038. if (this.packedFloat) {
  74039. defines += "#define PACKEDFLOAT 1";
  74040. }
  74041. this.blockCompilation = false;
  74042. _super.prototype.updateEffect.call(this, defines, null, null, {
  74043. varyingCount: varyingCount,
  74044. depCount: depCount
  74045. }, onCompiled, onError);
  74046. };
  74047. /**
  74048. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74049. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74050. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74051. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74052. * The gaps between physical kernels are compensated for in the weighting of the samples
  74053. * @param idealKernel Ideal blur kernel.
  74054. * @return Nearest best kernel.
  74055. */
  74056. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74057. var v = Math.round(idealKernel);
  74058. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74059. var k = _a[_i];
  74060. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74061. return Math.max(k, 3);
  74062. }
  74063. }
  74064. return Math.max(v, 3);
  74065. };
  74066. /**
  74067. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74068. * @param x The point on the Gaussian distribution to sample.
  74069. * @return the value of the Gaussian function at x.
  74070. */
  74071. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74072. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74073. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74074. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74075. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74076. // truncated at around 1.3% of peak strength.
  74077. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74078. var sigma = (1 / 3);
  74079. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74080. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74081. var weight = (1.0 / denominator) * Math.exp(exponent);
  74082. return weight;
  74083. };
  74084. /**
  74085. * Generates a string that can be used as a floating point number in GLSL.
  74086. * @param x Value to print.
  74087. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74088. * @return GLSL float string.
  74089. */
  74090. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74091. if (decimalFigures === void 0) { decimalFigures = 8; }
  74092. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74093. };
  74094. return BlurPostProcess;
  74095. }(BABYLON.PostProcess));
  74096. BABYLON.BlurPostProcess = BlurPostProcess;
  74097. })(BABYLON || (BABYLON = {}));
  74098. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74099. var BABYLON;
  74100. (function (BABYLON) {
  74101. /**
  74102. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74103. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74104. * based on samples that have a large difference in distance than the center pixel.
  74105. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74106. */
  74107. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74108. __extends(DepthOfFieldBlurPostProcess, _super);
  74109. /**
  74110. * Creates a new instance CircleOfConfusionPostProcess
  74111. * @param name The name of the effect.
  74112. * @param scene The scene the effect belongs to.
  74113. * @param direction The direction the blur should be applied.
  74114. * @param kernel The size of the kernel used to blur.
  74115. * @param options The required width/height ratio to downsize to before computing the render pass.
  74116. * @param camera The camera to apply the render pass to.
  74117. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74118. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74119. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74120. * @param engine The engine which the post process will be applied. (default: current engine)
  74121. * @param reusable If the post process can be reused on the same frame. (default: false)
  74122. * @param textureType Type of textures used when performing the post process. (default: 0)
  74123. * @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)
  74124. */
  74125. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74126. if (imageToBlur === void 0) { imageToBlur = null; }
  74127. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74128. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74129. if (blockCompilation === void 0) { blockCompilation = false; }
  74130. 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;
  74131. _this.direction = direction;
  74132. _this.onApplyObservable.add(function (effect) {
  74133. if (imageToBlur != null) {
  74134. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74135. }
  74136. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74137. if (scene.activeCamera) {
  74138. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74139. }
  74140. });
  74141. return _this;
  74142. }
  74143. return DepthOfFieldBlurPostProcess;
  74144. }(BABYLON.BlurPostProcess));
  74145. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74146. })(BABYLON || (BABYLON = {}));
  74147. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74148. var BABYLON;
  74149. (function (BABYLON) {
  74150. /**
  74151. * Options to be set when merging outputs from the default pipeline.
  74152. */
  74153. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74154. function DepthOfFieldMergePostProcessOptions() {
  74155. }
  74156. return DepthOfFieldMergePostProcessOptions;
  74157. }());
  74158. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74159. /**
  74160. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74161. */
  74162. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74163. __extends(DepthOfFieldMergePostProcess, _super);
  74164. /**
  74165. * Creates a new instance of DepthOfFieldMergePostProcess
  74166. * @param name The name of the effect.
  74167. * @param originalFromInput Post process which's input will be used for the merge.
  74168. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74169. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74170. * @param options The required width/height ratio to downsize to before computing the render pass.
  74171. * @param camera The camera to apply the render pass to.
  74172. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74173. * @param engine The engine which the post process will be applied. (default: current engine)
  74174. * @param reusable If the post process can be reused on the same frame. (default: false)
  74175. * @param textureType Type of textures used when performing the post process. (default: 0)
  74176. * @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)
  74177. */
  74178. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74179. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74180. if (blockCompilation === void 0) { blockCompilation = false; }
  74181. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74182. _this.blurSteps = blurSteps;
  74183. _this.onApplyObservable.add(function (effect) {
  74184. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74185. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74186. blurSteps.forEach(function (step, index) {
  74187. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74188. });
  74189. });
  74190. if (!blockCompilation) {
  74191. _this.updateEffect();
  74192. }
  74193. return _this;
  74194. }
  74195. /**
  74196. * Updates the effect with the current post process compile time values and recompiles the shader.
  74197. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74198. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74199. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74200. * @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
  74201. * @param onCompiled Called when the shader has been compiled.
  74202. * @param onError Called if there is an error when compiling a shader.
  74203. */
  74204. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74205. if (defines === void 0) { defines = null; }
  74206. if (uniforms === void 0) { uniforms = null; }
  74207. if (samplers === void 0) { samplers = null; }
  74208. if (!defines) {
  74209. defines = "";
  74210. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74211. }
  74212. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74213. };
  74214. return DepthOfFieldMergePostProcess;
  74215. }(BABYLON.PostProcess));
  74216. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74217. })(BABYLON || (BABYLON = {}));
  74218. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74219. var BABYLON;
  74220. (function (BABYLON) {
  74221. /**
  74222. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74223. */
  74224. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74225. __extends(CircleOfConfusionPostProcess, _super);
  74226. /**
  74227. * Creates a new instance CircleOfConfusionPostProcess
  74228. * @param name The name of the effect.
  74229. * @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.
  74230. * @param options The required width/height ratio to downsize to before computing the render pass.
  74231. * @param camera The camera to apply the render pass to.
  74232. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74233. * @param engine The engine which the post process will be applied. (default: current engine)
  74234. * @param reusable If the post process can be reused on the same frame. (default: false)
  74235. * @param textureType Type of textures used when performing the post process. (default: 0)
  74236. * @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)
  74237. */
  74238. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74239. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74240. if (blockCompilation === void 0) { blockCompilation = false; }
  74241. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74242. /**
  74243. * 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.
  74244. */
  74245. _this.lensSize = 50;
  74246. /**
  74247. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74248. */
  74249. _this.fStop = 1.4;
  74250. /**
  74251. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74252. */
  74253. _this.focusDistance = 2000;
  74254. /**
  74255. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74256. */
  74257. _this.focalLength = 50;
  74258. _this._depthTexture = null;
  74259. _this._depthTexture = depthTexture;
  74260. _this.onApplyObservable.add(function (effect) {
  74261. if (!_this._depthTexture) {
  74262. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74263. return;
  74264. }
  74265. effect.setTexture("depthSampler", _this._depthTexture);
  74266. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74267. var aperture = _this.lensSize / _this.fStop;
  74268. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74269. effect.setFloat('focusDistance', _this.focusDistance);
  74270. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74271. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74272. });
  74273. return _this;
  74274. }
  74275. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74276. /**
  74277. * 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.
  74278. */
  74279. set: function (value) {
  74280. this._depthTexture = value;
  74281. },
  74282. enumerable: true,
  74283. configurable: true
  74284. });
  74285. return CircleOfConfusionPostProcess;
  74286. }(BABYLON.PostProcess));
  74287. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74288. })(BABYLON || (BABYLON = {}));
  74289. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74290. var BABYLON;
  74291. (function (BABYLON) {
  74292. /**
  74293. * Specifies the level of max blur that should be applied when using the depth of field effect
  74294. */
  74295. var DepthOfFieldEffectBlurLevel;
  74296. (function (DepthOfFieldEffectBlurLevel) {
  74297. /**
  74298. * Subtle blur
  74299. */
  74300. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74301. /**
  74302. * Medium blur
  74303. */
  74304. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74305. /**
  74306. * Large blur
  74307. */
  74308. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74309. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74310. ;
  74311. /**
  74312. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74313. */
  74314. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74315. __extends(DepthOfFieldEffect, _super);
  74316. /**
  74317. * Creates a new instance DepthOfFieldEffect
  74318. * @param scene The scene the effect belongs to.
  74319. * @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.
  74320. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74321. * @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)
  74322. */
  74323. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74324. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74325. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74326. if (blockCompilation === void 0) { blockCompilation = false; }
  74327. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74328. return _this._effects;
  74329. }, true) || this;
  74330. /**
  74331. * Internal post processes in depth of field effect
  74332. */
  74333. _this._effects = [];
  74334. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74335. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74336. // 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)
  74337. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74338. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74339. _this._depthOfFieldBlurY = [];
  74340. _this._depthOfFieldBlurX = [];
  74341. var blurCount = 1;
  74342. var kernelSize = 15;
  74343. switch (blurLevel) {
  74344. case DepthOfFieldEffectBlurLevel.High: {
  74345. blurCount = 3;
  74346. kernelSize = 51;
  74347. break;
  74348. }
  74349. case DepthOfFieldEffectBlurLevel.Medium: {
  74350. blurCount = 2;
  74351. kernelSize = 31;
  74352. break;
  74353. }
  74354. default: {
  74355. kernelSize = 15;
  74356. blurCount = 1;
  74357. break;
  74358. }
  74359. }
  74360. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74361. var ratio = 1.0;
  74362. for (var i = 0; i < blurCount; i++) {
  74363. 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);
  74364. blurY.autoClear = false;
  74365. ratio = 0.75 / Math.pow(2, i);
  74366. 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);
  74367. blurX.autoClear = false;
  74368. _this._depthOfFieldBlurY.push(blurY);
  74369. _this._depthOfFieldBlurX.push(blurX);
  74370. }
  74371. // Set all post processes on the effect.
  74372. _this._effects = [_this._circleOfConfusion];
  74373. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74374. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74375. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74376. }
  74377. // Merge blurred images with original image based on circleOfConfusion
  74378. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74379. _this._dofMerge.autoClear = false;
  74380. _this._effects.push(_this._dofMerge);
  74381. return _this;
  74382. }
  74383. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74384. get: function () {
  74385. return this._circleOfConfusion.focalLength;
  74386. },
  74387. /**
  74388. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74389. */
  74390. set: function (value) {
  74391. this._circleOfConfusion.focalLength = value;
  74392. },
  74393. enumerable: true,
  74394. configurable: true
  74395. });
  74396. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74397. get: function () {
  74398. return this._circleOfConfusion.fStop;
  74399. },
  74400. /**
  74401. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74402. */
  74403. set: function (value) {
  74404. this._circleOfConfusion.fStop = value;
  74405. },
  74406. enumerable: true,
  74407. configurable: true
  74408. });
  74409. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74410. get: function () {
  74411. return this._circleOfConfusion.focusDistance;
  74412. },
  74413. /**
  74414. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74415. */
  74416. set: function (value) {
  74417. this._circleOfConfusion.focusDistance = value;
  74418. },
  74419. enumerable: true,
  74420. configurable: true
  74421. });
  74422. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74423. get: function () {
  74424. return this._circleOfConfusion.lensSize;
  74425. },
  74426. /**
  74427. * 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.
  74428. */
  74429. set: function (value) {
  74430. this._circleOfConfusion.lensSize = value;
  74431. },
  74432. enumerable: true,
  74433. configurable: true
  74434. });
  74435. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74436. /**
  74437. * 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.
  74438. */
  74439. set: function (value) {
  74440. this._circleOfConfusion.depthTexture = value;
  74441. },
  74442. enumerable: true,
  74443. configurable: true
  74444. });
  74445. /**
  74446. * Disposes each of the internal effects for a given camera.
  74447. * @param camera The camera to dispose the effect on.
  74448. */
  74449. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74450. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74451. this._effects[effectIndex].dispose(camera);
  74452. }
  74453. };
  74454. /**
  74455. * Internal
  74456. */
  74457. DepthOfFieldEffect.prototype._updateEffects = function () {
  74458. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74459. this._effects[effectIndex].updateEffect();
  74460. }
  74461. };
  74462. /**
  74463. * Internal
  74464. * @returns if all the contained post processes are ready.
  74465. */
  74466. DepthOfFieldEffect.prototype._isReady = function () {
  74467. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74468. if (!this._effects[effectIndex].isReady()) {
  74469. return false;
  74470. }
  74471. }
  74472. return true;
  74473. };
  74474. return DepthOfFieldEffect;
  74475. }(BABYLON.PostProcessRenderEffect));
  74476. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74477. })(BABYLON || (BABYLON = {}));
  74478. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74479. var BABYLON;
  74480. (function (BABYLON) {
  74481. /**
  74482. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74483. */
  74484. var BloomMergePostProcess = /** @class */ (function (_super) {
  74485. __extends(BloomMergePostProcess, _super);
  74486. /**
  74487. * Creates a new instance of @see BloomMergePostProcess
  74488. * @param name The name of the effect.
  74489. * @param originalFromInput Post process which's input will be used for the merge.
  74490. * @param blurred Blurred highlights post process which's output will be used.
  74491. * @param weight Weight of the bloom to be added to the original input.
  74492. * @param options The required width/height ratio to downsize to before computing the render pass.
  74493. * @param camera The camera to apply the render pass to.
  74494. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74495. * @param engine The engine which the post process will be applied. (default: current engine)
  74496. * @param reusable If the post process can be reused on the same frame. (default: false)
  74497. * @param textureType Type of textures used when performing the post process. (default: 0)
  74498. * @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)
  74499. */
  74500. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74501. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74502. if (blockCompilation === void 0) { blockCompilation = false; }
  74503. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74504. _this.weight = weight;
  74505. _this.onApplyObservable.add(function (effect) {
  74506. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74507. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74508. effect.setFloat("bloomWeight", _this.weight);
  74509. });
  74510. if (!blockCompilation) {
  74511. _this.updateEffect();
  74512. }
  74513. return _this;
  74514. }
  74515. return BloomMergePostProcess;
  74516. }(BABYLON.PostProcess));
  74517. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74518. })(BABYLON || (BABYLON = {}));
  74519. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74520. var BABYLON;
  74521. (function (BABYLON) {
  74522. /**
  74523. * 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.
  74524. */
  74525. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74526. __extends(ExtractHighlightsPostProcess, _super);
  74527. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74528. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74529. if (blockCompilation === void 0) { blockCompilation = false; }
  74530. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74531. /**
  74532. * The luminance threshold, pixels below this value will be set to black.
  74533. */
  74534. _this.threshold = 0.9;
  74535. /**
  74536. * Internal
  74537. */
  74538. _this._exposure = 1;
  74539. /**
  74540. * Post process which has the input texture to be used when performing highlight extraction
  74541. */
  74542. _this._inputPostProcess = null;
  74543. _this.onApplyObservable.add(function (effect) {
  74544. if (_this._inputPostProcess) {
  74545. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74546. }
  74547. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74548. effect.setFloat('exposure', _this._exposure);
  74549. });
  74550. return _this;
  74551. }
  74552. return ExtractHighlightsPostProcess;
  74553. }(BABYLON.PostProcess));
  74554. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74555. })(BABYLON || (BABYLON = {}));
  74556. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74557. var BABYLON;
  74558. (function (BABYLON) {
  74559. /**
  74560. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74561. */
  74562. var BloomEffect = /** @class */ (function (_super) {
  74563. __extends(BloomEffect, _super);
  74564. /**
  74565. * Creates a new instance of @see BloomEffect
  74566. * @param scene The scene the effect belongs to.
  74567. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74568. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74569. * @param bloomWeight The the strength of bloom.
  74570. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74571. * @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)
  74572. */
  74573. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74574. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74575. if (blockCompilation === void 0) { blockCompilation = false; }
  74576. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74577. return _this._effects;
  74578. }, true) || this;
  74579. _this.bloomScale = bloomScale;
  74580. /**
  74581. * Internal
  74582. */
  74583. _this._effects = [];
  74584. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74585. _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);
  74586. _this._blurX.alwaysForcePOT = true;
  74587. _this._blurX.autoClear = false;
  74588. _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);
  74589. _this._blurY.alwaysForcePOT = true;
  74590. _this._blurY.autoClear = false;
  74591. _this.kernel = bloomKernel;
  74592. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74593. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74594. _this._merge.autoClear = false;
  74595. _this._effects.push(_this._merge);
  74596. return _this;
  74597. }
  74598. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74599. /**
  74600. * The luminance threshold to find bright areas of the image to bloom.
  74601. */
  74602. get: function () {
  74603. return this._downscale.threshold;
  74604. },
  74605. set: function (value) {
  74606. this._downscale.threshold = value;
  74607. },
  74608. enumerable: true,
  74609. configurable: true
  74610. });
  74611. Object.defineProperty(BloomEffect.prototype, "weight", {
  74612. /**
  74613. * The strength of the bloom.
  74614. */
  74615. get: function () {
  74616. return this._merge.weight;
  74617. },
  74618. set: function (value) {
  74619. this._merge.weight = value;
  74620. },
  74621. enumerable: true,
  74622. configurable: true
  74623. });
  74624. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74625. /**
  74626. * Specifies the size of the bloom blur kernel, relative to the final output size
  74627. */
  74628. get: function () {
  74629. return this._blurX.kernel / this.bloomScale;
  74630. },
  74631. set: function (value) {
  74632. this._blurX.kernel = value * this.bloomScale;
  74633. this._blurY.kernel = value * this.bloomScale;
  74634. },
  74635. enumerable: true,
  74636. configurable: true
  74637. });
  74638. /**
  74639. * Disposes each of the internal effects for a given camera.
  74640. * @param camera The camera to dispose the effect on.
  74641. */
  74642. BloomEffect.prototype.disposeEffects = function (camera) {
  74643. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74644. this._effects[effectIndex].dispose(camera);
  74645. }
  74646. };
  74647. /**
  74648. * Internal
  74649. */
  74650. BloomEffect.prototype._updateEffects = function () {
  74651. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74652. this._effects[effectIndex].updateEffect();
  74653. }
  74654. };
  74655. /**
  74656. * Internal
  74657. * @returns if all the contained post processes are ready.
  74658. */
  74659. BloomEffect.prototype._isReady = function () {
  74660. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74661. if (!this._effects[effectIndex].isReady()) {
  74662. return false;
  74663. }
  74664. }
  74665. return true;
  74666. };
  74667. return BloomEffect;
  74668. }(BABYLON.PostProcessRenderEffect));
  74669. BABYLON.BloomEffect = BloomEffect;
  74670. })(BABYLON || (BABYLON = {}));
  74671. //# sourceMappingURL=babylon.bloomEffect.js.map
  74672. var BABYLON;
  74673. (function (BABYLON) {
  74674. /**
  74675. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74676. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74677. */
  74678. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74679. __extends(DefaultRenderingPipeline, _super);
  74680. /**
  74681. * @constructor
  74682. * @param {string} name - The rendering pipeline name
  74683. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74684. * @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)
  74685. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74686. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74687. */
  74688. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74689. if (automaticBuild === void 0) { automaticBuild = true; }
  74690. var _this = _super.call(this, scene.getEngine(), name) || this;
  74691. _this._originalCameras = [];
  74692. /**
  74693. * ID of the sharpen post process,
  74694. */
  74695. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74696. /**
  74697. * ID of the image processing post process;
  74698. */
  74699. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74700. /**
  74701. * ID of the Fast Approximate Anti-Aliasing post process;
  74702. */
  74703. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74704. /**
  74705. * ID of the chromatic aberration post process,
  74706. */
  74707. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74708. /**
  74709. * ID of the grain post process
  74710. */
  74711. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74712. /**
  74713. * Animations which can be used to tweak settings over a period of time
  74714. */
  74715. _this.animations = [];
  74716. _this._imageProcessingConfigurationObserver = null;
  74717. // Values
  74718. _this._sharpenEnabled = false;
  74719. _this._bloomEnabled = false;
  74720. _this._depthOfFieldEnabled = false;
  74721. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74722. _this._fxaaEnabled = false;
  74723. _this._imageProcessingEnabled = true;
  74724. _this._bloomScale = 0.5;
  74725. _this._chromaticAberrationEnabled = false;
  74726. _this._grainEnabled = false;
  74727. _this._buildAllowed = true;
  74728. _this._resizeObserver = null;
  74729. _this._hardwareScaleLevel = 1.0;
  74730. _this._bloomKernel = 64;
  74731. /**
  74732. * Specifies the weight of the bloom in the final rendering
  74733. */
  74734. _this._bloomWeight = 0.15;
  74735. /**
  74736. * Specifies the luma threshold for the area that will be blurred by the bloom
  74737. */
  74738. _this._bloomThreshold = 0.9;
  74739. _this._samples = 1;
  74740. _this._hasCleared = false;
  74741. _this._prevPostProcess = null;
  74742. _this._prevPrevPostProcess = null;
  74743. _this._cameras = cameras || [];
  74744. _this._originalCameras = _this._cameras.slice();
  74745. _this._buildAllowed = automaticBuild;
  74746. // Initialize
  74747. _this._scene = scene;
  74748. var caps = _this._scene.getEngine().getCaps();
  74749. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74750. // Misc
  74751. if (_this._hdr) {
  74752. if (caps.textureHalfFloatRender) {
  74753. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74754. }
  74755. else if (caps.textureFloatRender) {
  74756. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74757. }
  74758. }
  74759. else {
  74760. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74761. }
  74762. // Attach
  74763. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74764. var engine = _this._scene.getEngine();
  74765. // Create post processes before hand so they can be modified before enabled.
  74766. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74767. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74768. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74769. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74770. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74771. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74772. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74773. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74774. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74775. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74776. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74777. _this.bloomKernel = _this.bloomKernel;
  74778. });
  74779. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74780. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74781. });
  74782. _this._buildPipeline();
  74783. return _this;
  74784. }
  74785. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74786. get: function () {
  74787. return this._sharpenEnabled;
  74788. },
  74789. /**
  74790. * Enable or disable the sharpen process from the pipeline
  74791. */
  74792. set: function (enabled) {
  74793. if (this._sharpenEnabled === enabled) {
  74794. return;
  74795. }
  74796. this._sharpenEnabled = enabled;
  74797. this._buildPipeline();
  74798. },
  74799. enumerable: true,
  74800. configurable: true
  74801. });
  74802. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74803. /**
  74804. * Specifies the size of the bloom blur kernel, relative to the final output size
  74805. */
  74806. get: function () {
  74807. return this._bloomKernel;
  74808. },
  74809. set: function (value) {
  74810. this._bloomKernel = value;
  74811. this.bloom.kernel = value / this._hardwareScaleLevel;
  74812. },
  74813. enumerable: true,
  74814. configurable: true
  74815. });
  74816. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74817. get: function () {
  74818. return this._bloomWeight;
  74819. },
  74820. /**
  74821. * The strength of the bloom.
  74822. */
  74823. set: function (value) {
  74824. if (this._bloomWeight === value) {
  74825. return;
  74826. }
  74827. this.bloom.weight = value;
  74828. this._bloomWeight = value;
  74829. },
  74830. enumerable: true,
  74831. configurable: true
  74832. });
  74833. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74834. get: function () {
  74835. return this._bloomThreshold;
  74836. },
  74837. /**
  74838. * The strength of the bloom.
  74839. */
  74840. set: function (value) {
  74841. if (this._bloomThreshold === value) {
  74842. return;
  74843. }
  74844. this.bloom.threshold = value;
  74845. this._bloomThreshold = value;
  74846. },
  74847. enumerable: true,
  74848. configurable: true
  74849. });
  74850. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74851. get: function () {
  74852. return this._bloomScale;
  74853. },
  74854. /**
  74855. * The scale of the bloom, lower value will provide better performance.
  74856. */
  74857. set: function (value) {
  74858. if (this._bloomScale === value) {
  74859. return;
  74860. }
  74861. this._bloomScale = value;
  74862. // recreate bloom and dispose old as this setting is not dynamic
  74863. this._rebuildBloom();
  74864. this._buildPipeline();
  74865. },
  74866. enumerable: true,
  74867. configurable: true
  74868. });
  74869. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  74870. get: function () {
  74871. return this._bloomEnabled;
  74872. },
  74873. /**
  74874. * Enable or disable the bloom from the pipeline
  74875. */
  74876. set: function (enabled) {
  74877. if (this._bloomEnabled === enabled) {
  74878. return;
  74879. }
  74880. this._bloomEnabled = enabled;
  74881. this._buildPipeline();
  74882. },
  74883. enumerable: true,
  74884. configurable: true
  74885. });
  74886. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  74887. // recreate bloom and dispose old as this setting is not dynamic
  74888. var oldBloom = this.bloom;
  74889. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  74890. this.bloom.threshold = oldBloom.threshold;
  74891. for (var i = 0; i < this._cameras.length; i++) {
  74892. oldBloom.disposeEffects(this._cameras[i]);
  74893. }
  74894. };
  74895. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  74896. /**
  74897. * If the depth of field is enabled.
  74898. */
  74899. get: function () {
  74900. return this._depthOfFieldEnabled;
  74901. },
  74902. set: function (enabled) {
  74903. if (this._depthOfFieldEnabled === enabled) {
  74904. return;
  74905. }
  74906. this._depthOfFieldEnabled = enabled;
  74907. this._buildPipeline();
  74908. },
  74909. enumerable: true,
  74910. configurable: true
  74911. });
  74912. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  74913. /**
  74914. * Blur level of the depth of field effect. (Higher blur will effect performance)
  74915. */
  74916. get: function () {
  74917. return this._depthOfFieldBlurLevel;
  74918. },
  74919. set: function (value) {
  74920. if (this._depthOfFieldBlurLevel === value) {
  74921. return;
  74922. }
  74923. this._depthOfFieldBlurLevel = value;
  74924. // recreate dof and dispose old as this setting is not dynamic
  74925. var oldDof = this.depthOfField;
  74926. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  74927. this.depthOfField.focalLength = oldDof.focalLength;
  74928. this.depthOfField.focusDistance = oldDof.focusDistance;
  74929. this.depthOfField.fStop = oldDof.fStop;
  74930. this.depthOfField.lensSize = oldDof.lensSize;
  74931. for (var i = 0; i < this._cameras.length; i++) {
  74932. oldDof.disposeEffects(this._cameras[i]);
  74933. }
  74934. this._buildPipeline();
  74935. },
  74936. enumerable: true,
  74937. configurable: true
  74938. });
  74939. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  74940. get: function () {
  74941. return this._fxaaEnabled;
  74942. },
  74943. /**
  74944. * If the anti aliasing is enabled.
  74945. */
  74946. set: function (enabled) {
  74947. if (this._fxaaEnabled === enabled) {
  74948. return;
  74949. }
  74950. this._fxaaEnabled = enabled;
  74951. this._buildPipeline();
  74952. },
  74953. enumerable: true,
  74954. configurable: true
  74955. });
  74956. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  74957. get: function () {
  74958. return this._samples;
  74959. },
  74960. /**
  74961. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  74962. */
  74963. set: function (sampleCount) {
  74964. if (this._samples === sampleCount) {
  74965. return;
  74966. }
  74967. this._samples = sampleCount;
  74968. this._buildPipeline();
  74969. },
  74970. enumerable: true,
  74971. configurable: true
  74972. });
  74973. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  74974. get: function () {
  74975. return this._imageProcessingEnabled;
  74976. },
  74977. /**
  74978. * If image processing is enabled.
  74979. */
  74980. set: function (enabled) {
  74981. if (this._imageProcessingEnabled === enabled) {
  74982. return;
  74983. }
  74984. this._imageProcessingEnabled = enabled;
  74985. this._buildPipeline();
  74986. },
  74987. enumerable: true,
  74988. configurable: true
  74989. });
  74990. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  74991. get: function () {
  74992. return this._chromaticAberrationEnabled;
  74993. },
  74994. /**
  74995. * Enable or disable the chromaticAberration process from the pipeline
  74996. */
  74997. set: function (enabled) {
  74998. if (this._chromaticAberrationEnabled === enabled) {
  74999. return;
  75000. }
  75001. this._chromaticAberrationEnabled = enabled;
  75002. this._buildPipeline();
  75003. },
  75004. enumerable: true,
  75005. configurable: true
  75006. });
  75007. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75008. get: function () {
  75009. return this._grainEnabled;
  75010. },
  75011. /**
  75012. * Enable or disable the grain process from the pipeline
  75013. */
  75014. set: function (enabled) {
  75015. if (this._grainEnabled === enabled) {
  75016. return;
  75017. }
  75018. this._grainEnabled = enabled;
  75019. this._buildPipeline();
  75020. },
  75021. enumerable: true,
  75022. configurable: true
  75023. });
  75024. /**
  75025. * Force the compilation of the entire pipeline.
  75026. */
  75027. DefaultRenderingPipeline.prototype.prepare = function () {
  75028. var previousState = this._buildAllowed;
  75029. this._buildAllowed = true;
  75030. this._buildPipeline();
  75031. this._buildAllowed = previousState;
  75032. };
  75033. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75034. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75035. if (this._hasCleared) {
  75036. postProcess.autoClear = false;
  75037. }
  75038. else {
  75039. postProcess.autoClear = true;
  75040. this._scene.autoClear = false;
  75041. this._hasCleared = true;
  75042. }
  75043. if (!skipTextureSharing) {
  75044. if (this._prevPrevPostProcess) {
  75045. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75046. }
  75047. else {
  75048. postProcess.useOwnOutput();
  75049. }
  75050. if (this._prevPostProcess) {
  75051. this._prevPrevPostProcess = this._prevPostProcess;
  75052. }
  75053. this._prevPostProcess = postProcess;
  75054. }
  75055. };
  75056. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75057. var _this = this;
  75058. if (!this._buildAllowed) {
  75059. return;
  75060. }
  75061. this._scene.autoClear = true;
  75062. var engine = this._scene.getEngine();
  75063. this._disposePostProcesses();
  75064. if (this._cameras !== null) {
  75065. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75066. // get back cameras to be used to reattach pipeline
  75067. this._cameras = this._originalCameras.slice();
  75068. }
  75069. this._reset();
  75070. this._prevPostProcess = null;
  75071. this._prevPrevPostProcess = null;
  75072. this._hasCleared = false;
  75073. if (this.depthOfFieldEnabled) {
  75074. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75075. this.depthOfField.depthTexture = depthTexture;
  75076. if (!this.depthOfField._isReady()) {
  75077. this.depthOfField._updateEffects();
  75078. }
  75079. this.addEffect(this.depthOfField);
  75080. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75081. }
  75082. if (this.bloomEnabled) {
  75083. if (!this.bloom._isReady()) {
  75084. this.bloom._updateEffects();
  75085. }
  75086. this.addEffect(this.bloom);
  75087. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75088. }
  75089. if (this._imageProcessingEnabled) {
  75090. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75091. if (this._hdr) {
  75092. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75093. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75094. }
  75095. else {
  75096. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75097. }
  75098. }
  75099. if (this.sharpenEnabled) {
  75100. if (!this.sharpen.isReady()) {
  75101. this.sharpen.updateEffect();
  75102. }
  75103. this.addEffect(this._sharpenEffect);
  75104. this._setAutoClearAndTextureSharing(this.sharpen);
  75105. }
  75106. if (this.grainEnabled) {
  75107. if (!this.grain.isReady()) {
  75108. this.grain.updateEffect();
  75109. }
  75110. this.addEffect(this._grainEffect);
  75111. this._setAutoClearAndTextureSharing(this.grain);
  75112. }
  75113. if (this.chromaticAberrationEnabled) {
  75114. if (!this.chromaticAberration.isReady()) {
  75115. this.chromaticAberration.updateEffect();
  75116. }
  75117. this.addEffect(this._chromaticAberrationEffect);
  75118. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75119. }
  75120. if (this.fxaaEnabled) {
  75121. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75122. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75123. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75124. }
  75125. if (this._cameras !== null) {
  75126. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75127. }
  75128. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75129. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75130. }
  75131. };
  75132. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75133. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75134. for (var i = 0; i < this._cameras.length; i++) {
  75135. var camera = this._cameras[i];
  75136. if (this.imageProcessing) {
  75137. this.imageProcessing.dispose(camera);
  75138. }
  75139. if (this.fxaa) {
  75140. this.fxaa.dispose(camera);
  75141. }
  75142. // These are created in the constructor and should not be disposed on every pipeline change
  75143. if (disposeNonRecreated) {
  75144. if (this.sharpen) {
  75145. this.sharpen.dispose(camera);
  75146. }
  75147. if (this.depthOfField) {
  75148. this.depthOfField.disposeEffects(camera);
  75149. }
  75150. if (this.bloom) {
  75151. this.bloom.disposeEffects(camera);
  75152. }
  75153. if (this.chromaticAberration) {
  75154. this.chromaticAberration.dispose(camera);
  75155. }
  75156. if (this.grain) {
  75157. this.grain.dispose(camera);
  75158. }
  75159. }
  75160. }
  75161. this.imageProcessing = null;
  75162. this.fxaa = null;
  75163. if (disposeNonRecreated) {
  75164. this.sharpen = null;
  75165. this._sharpenEffect = null;
  75166. this.depthOfField = null;
  75167. this.bloom = null;
  75168. this.chromaticAberration = null;
  75169. this._chromaticAberrationEffect = null;
  75170. this.grain = null;
  75171. this._grainEffect = null;
  75172. }
  75173. };
  75174. /**
  75175. * Dispose of the pipeline and stop all post processes
  75176. */
  75177. DefaultRenderingPipeline.prototype.dispose = function () {
  75178. this._disposePostProcesses(true);
  75179. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75180. this._scene.autoClear = true;
  75181. if (this._resizeObserver) {
  75182. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75183. this._resizeObserver = null;
  75184. }
  75185. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75186. _super.prototype.dispose.call(this);
  75187. };
  75188. /**
  75189. * Serialize the rendering pipeline (Used when exporting)
  75190. * @returns the serialized object
  75191. */
  75192. DefaultRenderingPipeline.prototype.serialize = function () {
  75193. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75194. serializationObject.customType = "DefaultRenderingPipeline";
  75195. return serializationObject;
  75196. };
  75197. /**
  75198. * Parse the serialized pipeline
  75199. * @param source Source pipeline.
  75200. * @param scene The scene to load the pipeline to.
  75201. * @param rootUrl The URL of the serialized pipeline.
  75202. * @returns An instantiated pipeline from the serialized object.
  75203. */
  75204. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75205. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75206. };
  75207. __decorate([
  75208. BABYLON.serialize()
  75209. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75210. __decorate([
  75211. BABYLON.serialize()
  75212. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75213. __decorate([
  75214. BABYLON.serialize()
  75215. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75216. __decorate([
  75217. BABYLON.serialize()
  75218. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75219. __decorate([
  75220. BABYLON.serialize()
  75221. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75222. __decorate([
  75223. BABYLON.serialize()
  75224. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75225. __decorate([
  75226. BABYLON.serialize()
  75227. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75228. __decorate([
  75229. BABYLON.serialize()
  75230. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75231. __decorate([
  75232. BABYLON.serialize()
  75233. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75234. __decorate([
  75235. BABYLON.serialize()
  75236. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75237. __decorate([
  75238. BABYLON.serialize()
  75239. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75240. __decorate([
  75241. BABYLON.serialize()
  75242. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75243. __decorate([
  75244. BABYLON.serialize()
  75245. ], DefaultRenderingPipeline.prototype, "samples", null);
  75246. __decorate([
  75247. BABYLON.serialize()
  75248. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75249. __decorate([
  75250. BABYLON.serialize()
  75251. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75252. __decorate([
  75253. BABYLON.serialize()
  75254. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75255. return DefaultRenderingPipeline;
  75256. }(BABYLON.PostProcessRenderPipeline));
  75257. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75258. })(BABYLON || (BABYLON = {}));
  75259. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75260. var BABYLON;
  75261. (function (BABYLON) {
  75262. /**
  75263. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75264. */
  75265. var GeometryBufferRenderer = /** @class */ (function () {
  75266. /**
  75267. * Creates a new G Buffer for the scene
  75268. * @param scene The scene the buffer belongs to
  75269. * @param ratio How big is the buffer related to the main canvas.
  75270. */
  75271. function GeometryBufferRenderer(scene, ratio) {
  75272. if (ratio === void 0) { ratio = 1; }
  75273. this._enablePosition = false;
  75274. this._scene = scene;
  75275. this._ratio = ratio;
  75276. // Render target
  75277. this._createRenderTargets();
  75278. }
  75279. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75280. /**
  75281. * Set the render list (meshes to be rendered) used in the G buffer.
  75282. */
  75283. set: function (meshes) {
  75284. this._multiRenderTarget.renderList = meshes;
  75285. },
  75286. enumerable: true,
  75287. configurable: true
  75288. });
  75289. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75290. /**
  75291. * Gets wether or not G buffer are supported by the running hardware.
  75292. * This requires draw buffer supports
  75293. */
  75294. get: function () {
  75295. return this._multiRenderTarget.isSupported;
  75296. },
  75297. enumerable: true,
  75298. configurable: true
  75299. });
  75300. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75301. /**
  75302. * Gets wether or not position are enabled for the G buffer.
  75303. */
  75304. get: function () {
  75305. return this._enablePosition;
  75306. },
  75307. /**
  75308. * Sets wether or not position are enabled for the G buffer.
  75309. */
  75310. set: function (enable) {
  75311. this._enablePosition = enable;
  75312. this.dispose();
  75313. this._createRenderTargets();
  75314. },
  75315. enumerable: true,
  75316. configurable: true
  75317. });
  75318. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75319. /**
  75320. * Gets the scene associated with the buffer.
  75321. */
  75322. get: function () {
  75323. return this._scene;
  75324. },
  75325. enumerable: true,
  75326. configurable: true
  75327. });
  75328. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75329. /**
  75330. * Gets the ratio used by the buffer during its creation.
  75331. * How big is the buffer related to the main canvas.
  75332. */
  75333. get: function () {
  75334. return this._ratio;
  75335. },
  75336. enumerable: true,
  75337. configurable: true
  75338. });
  75339. /**
  75340. * Checks wether everything is ready to render a submesh to the G buffer.
  75341. * @param subMesh the submesh to check readiness for
  75342. * @param useInstances is the mesh drawn using instance or not
  75343. * @returns true if ready otherwise false
  75344. */
  75345. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75346. var material = subMesh.getMaterial();
  75347. if (material && material.disableDepthWrite) {
  75348. return false;
  75349. }
  75350. var defines = [];
  75351. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75352. var mesh = subMesh.getMesh();
  75353. // Alpha test
  75354. if (material && material.needAlphaTesting()) {
  75355. defines.push("#define ALPHATEST");
  75356. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75357. attribs.push(BABYLON.VertexBuffer.UVKind);
  75358. defines.push("#define UV1");
  75359. }
  75360. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75361. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75362. defines.push("#define UV2");
  75363. }
  75364. }
  75365. // Buffers
  75366. if (this._enablePosition) {
  75367. defines.push("#define POSITION");
  75368. }
  75369. // Bones
  75370. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75371. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75372. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75373. if (mesh.numBoneInfluencers > 4) {
  75374. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75375. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75376. }
  75377. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75378. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75379. }
  75380. else {
  75381. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75382. }
  75383. // Instances
  75384. if (useInstances) {
  75385. defines.push("#define INSTANCES");
  75386. attribs.push("world0");
  75387. attribs.push("world1");
  75388. attribs.push("world2");
  75389. attribs.push("world3");
  75390. }
  75391. // Get correct effect
  75392. var join = defines.join("\n");
  75393. if (this._cachedDefines !== join) {
  75394. this._cachedDefines = join;
  75395. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75396. }
  75397. return this._effect.isReady();
  75398. };
  75399. /**
  75400. * Gets the current underlying G Buffer.
  75401. * @returns the buffer
  75402. */
  75403. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75404. return this._multiRenderTarget;
  75405. };
  75406. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75407. /**
  75408. * Gets the number of samples used to render the buffer (anti aliasing).
  75409. */
  75410. get: function () {
  75411. return this._multiRenderTarget.samples;
  75412. },
  75413. /**
  75414. * Sets the number of samples used to render the buffer (anti aliasing).
  75415. */
  75416. set: function (value) {
  75417. this._multiRenderTarget.samples = value;
  75418. },
  75419. enumerable: true,
  75420. configurable: true
  75421. });
  75422. /**
  75423. * Disposes the renderer and frees up associated resources.
  75424. */
  75425. GeometryBufferRenderer.prototype.dispose = function () {
  75426. this.getGBuffer().dispose();
  75427. };
  75428. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75429. var _this = this;
  75430. var engine = this._scene.getEngine();
  75431. var count = this._enablePosition ? 3 : 2;
  75432. 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 });
  75433. if (!this.isSupported) {
  75434. return;
  75435. }
  75436. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75437. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75438. this._multiRenderTarget.refreshRate = 1;
  75439. this._multiRenderTarget.renderParticles = false;
  75440. this._multiRenderTarget.renderList = null;
  75441. // set default depth value to 1.0 (far away)
  75442. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75443. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75444. });
  75445. // Custom render function
  75446. var renderSubMesh = function (subMesh) {
  75447. var mesh = subMesh.getRenderingMesh();
  75448. var scene = _this._scene;
  75449. var engine = scene.getEngine();
  75450. var material = subMesh.getMaterial();
  75451. if (!material) {
  75452. return;
  75453. }
  75454. // Culling
  75455. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75456. // Managing instances
  75457. var batch = mesh._getInstancesRenderList(subMesh._id);
  75458. if (batch.mustReturn) {
  75459. return;
  75460. }
  75461. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75462. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75463. engine.enableEffect(_this._effect);
  75464. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75465. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75466. _this._effect.setMatrix("view", scene.getViewMatrix());
  75467. // Alpha test
  75468. if (material && material.needAlphaTesting()) {
  75469. var alphaTexture = material.getAlphaTestTexture();
  75470. if (alphaTexture) {
  75471. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75472. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75473. }
  75474. }
  75475. // Bones
  75476. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75477. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75478. }
  75479. // Draw
  75480. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75481. }
  75482. };
  75483. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75484. var index;
  75485. if (depthOnlySubMeshes.length) {
  75486. engine.setColorWrite(false);
  75487. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75488. renderSubMesh(depthOnlySubMeshes.data[index]);
  75489. }
  75490. engine.setColorWrite(true);
  75491. }
  75492. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75493. renderSubMesh(opaqueSubMeshes.data[index]);
  75494. }
  75495. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75496. renderSubMesh(alphaTestSubMeshes.data[index]);
  75497. }
  75498. };
  75499. };
  75500. return GeometryBufferRenderer;
  75501. }());
  75502. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75503. })(BABYLON || (BABYLON = {}));
  75504. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75505. var BABYLON;
  75506. (function (BABYLON) {
  75507. var RefractionPostProcess = /** @class */ (function (_super) {
  75508. __extends(RefractionPostProcess, _super);
  75509. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75510. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75511. _this.color = color;
  75512. _this.depth = depth;
  75513. _this.colorLevel = colorLevel;
  75514. _this._ownRefractionTexture = true;
  75515. _this.onActivateObservable.add(function (cam) {
  75516. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75517. });
  75518. _this.onApplyObservable.add(function (effect) {
  75519. effect.setColor3("baseColor", _this.color);
  75520. effect.setFloat("depth", _this.depth);
  75521. effect.setFloat("colorLevel", _this.colorLevel);
  75522. effect.setTexture("refractionSampler", _this._refTexture);
  75523. });
  75524. return _this;
  75525. }
  75526. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75527. /**
  75528. * Gets or sets the refraction texture
  75529. * Please note that you are responsible for disposing the texture if you set it manually
  75530. */
  75531. get: function () {
  75532. return this._refTexture;
  75533. },
  75534. set: function (value) {
  75535. if (this._refTexture && this._ownRefractionTexture) {
  75536. this._refTexture.dispose();
  75537. }
  75538. this._refTexture = value;
  75539. this._ownRefractionTexture = false;
  75540. },
  75541. enumerable: true,
  75542. configurable: true
  75543. });
  75544. // Methods
  75545. RefractionPostProcess.prototype.dispose = function (camera) {
  75546. if (this._refTexture && this._ownRefractionTexture) {
  75547. this._refTexture.dispose();
  75548. this._refTexture = null;
  75549. }
  75550. _super.prototype.dispose.call(this, camera);
  75551. };
  75552. return RefractionPostProcess;
  75553. }(BABYLON.PostProcess));
  75554. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75555. })(BABYLON || (BABYLON = {}));
  75556. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75557. var BABYLON;
  75558. (function (BABYLON) {
  75559. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75560. __extends(BlackAndWhitePostProcess, _super);
  75561. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75562. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75563. _this.degree = 1;
  75564. _this.onApplyObservable.add(function (effect) {
  75565. effect.setFloat("degree", _this.degree);
  75566. });
  75567. return _this;
  75568. }
  75569. return BlackAndWhitePostProcess;
  75570. }(BABYLON.PostProcess));
  75571. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75572. })(BABYLON || (BABYLON = {}));
  75573. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75574. var BABYLON;
  75575. (function (BABYLON) {
  75576. /**
  75577. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75578. * input texture to perform effects such as edge detection or sharpening
  75579. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75580. */
  75581. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75582. __extends(ConvolutionPostProcess, _super);
  75583. /**
  75584. * Creates a new instance ConvolutionPostProcess
  75585. * @param name The name of the effect.
  75586. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75587. * @param options The required width/height ratio to downsize to before computing the render pass.
  75588. * @param camera The camera to apply the render pass to.
  75589. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75590. * @param engine The engine which the post process will be applied. (default: current engine)
  75591. * @param reusable If the post process can be reused on the same frame. (default: false)
  75592. * @param textureType Type of textures used when performing the post process. (default: 0)
  75593. */
  75594. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75596. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75597. _this.kernel = kernel;
  75598. _this.onApply = function (effect) {
  75599. effect.setFloat2("screenSize", _this.width, _this.height);
  75600. effect.setArray("kernel", _this.kernel);
  75601. };
  75602. return _this;
  75603. }
  75604. // Statics
  75605. /**
  75606. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75607. */
  75608. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75609. /**
  75610. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75611. */
  75612. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75613. /**
  75614. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75615. */
  75616. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75617. /**
  75618. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75619. */
  75620. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75621. /**
  75622. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75623. */
  75624. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75625. /**
  75626. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75627. */
  75628. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75629. return ConvolutionPostProcess;
  75630. }(BABYLON.PostProcess));
  75631. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75632. })(BABYLON || (BABYLON = {}));
  75633. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75634. var BABYLON;
  75635. (function (BABYLON) {
  75636. var FilterPostProcess = /** @class */ (function (_super) {
  75637. __extends(FilterPostProcess, _super);
  75638. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75639. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75640. _this.kernelMatrix = kernelMatrix;
  75641. _this.onApply = function (effect) {
  75642. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75643. };
  75644. return _this;
  75645. }
  75646. return FilterPostProcess;
  75647. }(BABYLON.PostProcess));
  75648. BABYLON.FilterPostProcess = FilterPostProcess;
  75649. })(BABYLON || (BABYLON = {}));
  75650. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75651. var BABYLON;
  75652. (function (BABYLON) {
  75653. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75654. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75655. __extends(VolumetricLightScatteringPostProcess, _super);
  75656. /**
  75657. * @constructor
  75658. * @param {string} name - The post-process name
  75659. * @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)
  75660. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75661. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75662. * @param {number} samples - The post-process quality, default 100
  75663. * @param {number} samplingMode - The post-process filtering mode
  75664. * @param {BABYLON.Engine} engine - The babylon engine
  75665. * @param {boolean} reusable - If the post-process is reusable
  75666. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75667. */
  75668. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75669. if (samples === void 0) { samples = 100; }
  75670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75671. 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;
  75672. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75673. /**
  75674. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75675. */
  75676. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75677. /**
  75678. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75679. */
  75680. _this.useCustomMeshPosition = false;
  75681. /**
  75682. * If the post-process should inverse the light scattering direction
  75683. */
  75684. _this.invert = true;
  75685. /**
  75686. * Array containing the excluded meshes not rendered in the internal pass
  75687. */
  75688. _this.excludedMeshes = new Array();
  75689. /**
  75690. * Controls the overall intensity of the post-process
  75691. */
  75692. _this.exposure = 0.3;
  75693. /**
  75694. * Dissipates each sample's contribution in range [0, 1]
  75695. */
  75696. _this.decay = 0.96815;
  75697. /**
  75698. * Controls the overall intensity of each sample
  75699. */
  75700. _this.weight = 0.58767;
  75701. /**
  75702. * Controls the density of each sample
  75703. */
  75704. _this.density = 0.926;
  75705. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75706. engine = scene.getEngine();
  75707. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75708. // Configure mesh
  75709. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75710. // Configure
  75711. _this._createPass(scene, ratio.passRatio || ratio);
  75712. _this.onActivate = function (camera) {
  75713. if (!_this.isSupported) {
  75714. _this.dispose(camera);
  75715. }
  75716. _this.onActivate = null;
  75717. };
  75718. _this.onApplyObservable.add(function (effect) {
  75719. _this._updateMeshScreenCoordinates(scene);
  75720. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75721. effect.setFloat("exposure", _this.exposure);
  75722. effect.setFloat("decay", _this.decay);
  75723. effect.setFloat("weight", _this.weight);
  75724. effect.setFloat("density", _this.density);
  75725. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75726. });
  75727. return _this;
  75728. }
  75729. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75730. get: function () {
  75731. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75732. return false;
  75733. },
  75734. set: function (useDiffuseColor) {
  75735. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75736. },
  75737. enumerable: true,
  75738. configurable: true
  75739. });
  75740. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75741. return "VolumetricLightScatteringPostProcess";
  75742. };
  75743. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75744. var mesh = subMesh.getMesh();
  75745. // Render this.mesh as default
  75746. if (mesh === this.mesh && mesh.material) {
  75747. return mesh.material.isReady(mesh);
  75748. }
  75749. var defines = [];
  75750. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75751. var material = subMesh.getMaterial();
  75752. // Alpha test
  75753. if (material) {
  75754. if (material.needAlphaTesting()) {
  75755. defines.push("#define ALPHATEST");
  75756. }
  75757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75758. attribs.push(BABYLON.VertexBuffer.UVKind);
  75759. defines.push("#define UV1");
  75760. }
  75761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75762. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75763. defines.push("#define UV2");
  75764. }
  75765. }
  75766. // Bones
  75767. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75768. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75769. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75770. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75771. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75772. }
  75773. else {
  75774. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75775. }
  75776. // Instances
  75777. if (useInstances) {
  75778. defines.push("#define INSTANCES");
  75779. attribs.push("world0");
  75780. attribs.push("world1");
  75781. attribs.push("world2");
  75782. attribs.push("world3");
  75783. }
  75784. // Get correct effect
  75785. var join = defines.join("\n");
  75786. if (this._cachedDefines !== join) {
  75787. this._cachedDefines = join;
  75788. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75789. }
  75790. return this._volumetricLightScatteringPass.isReady();
  75791. };
  75792. /**
  75793. * Sets the new light position for light scattering effect
  75794. * @param {BABYLON.Vector3} The new custom light position
  75795. */
  75796. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75797. this.customMeshPosition = position;
  75798. };
  75799. /**
  75800. * Returns the light position for light scattering effect
  75801. * @return {BABYLON.Vector3} The custom light position
  75802. */
  75803. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75804. return this.customMeshPosition;
  75805. };
  75806. /**
  75807. * Disposes the internal assets and detaches the post-process from the camera
  75808. */
  75809. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75810. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75811. if (rttIndex !== -1) {
  75812. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75813. }
  75814. this._volumetricLightScatteringRTT.dispose();
  75815. _super.prototype.dispose.call(this, camera);
  75816. };
  75817. /**
  75818. * Returns the render target texture used by the post-process
  75819. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75820. */
  75821. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75822. return this._volumetricLightScatteringRTT;
  75823. };
  75824. // Private methods
  75825. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75826. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75827. return true;
  75828. }
  75829. return false;
  75830. };
  75831. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75832. var _this = this;
  75833. var engine = scene.getEngine();
  75834. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75835. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75836. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75837. this._volumetricLightScatteringRTT.renderList = null;
  75838. this._volumetricLightScatteringRTT.renderParticles = false;
  75839. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75840. var camera = this.getCamera();
  75841. if (camera) {
  75842. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75843. }
  75844. else {
  75845. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75846. }
  75847. // Custom render function for submeshes
  75848. var renderSubMesh = function (subMesh) {
  75849. var mesh = subMesh.getRenderingMesh();
  75850. if (_this._meshExcluded(mesh)) {
  75851. return;
  75852. }
  75853. var material = subMesh.getMaterial();
  75854. if (!material) {
  75855. return;
  75856. }
  75857. var scene = mesh.getScene();
  75858. var engine = scene.getEngine();
  75859. // Culling
  75860. engine.setState(material.backFaceCulling);
  75861. // Managing instances
  75862. var batch = mesh._getInstancesRenderList(subMesh._id);
  75863. if (batch.mustReturn) {
  75864. return;
  75865. }
  75866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75867. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  75868. var effect = _this._volumetricLightScatteringPass;
  75869. if (mesh === _this.mesh) {
  75870. if (subMesh.effect) {
  75871. effect = subMesh.effect;
  75872. }
  75873. else {
  75874. effect = material.getEffect();
  75875. }
  75876. }
  75877. engine.enableEffect(effect);
  75878. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  75879. if (mesh === _this.mesh) {
  75880. material.bind(mesh.getWorldMatrix(), mesh);
  75881. }
  75882. else {
  75883. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  75884. // Alpha test
  75885. if (material && material.needAlphaTesting()) {
  75886. var alphaTexture = material.getAlphaTestTexture();
  75887. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  75888. if (alphaTexture) {
  75889. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75890. }
  75891. }
  75892. // Bones
  75893. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75894. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75895. }
  75896. }
  75897. // Draw
  75898. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  75899. }
  75900. };
  75901. // Render target texture callbacks
  75902. var savedSceneClearColor;
  75903. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  75904. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  75905. savedSceneClearColor = scene.clearColor;
  75906. scene.clearColor = sceneClearColor;
  75907. });
  75908. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  75909. scene.clearColor = savedSceneClearColor;
  75910. });
  75911. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75912. var engine = scene.getEngine();
  75913. var index;
  75914. if (depthOnlySubMeshes.length) {
  75915. engine.setColorWrite(false);
  75916. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75917. renderSubMesh(depthOnlySubMeshes.data[index]);
  75918. }
  75919. engine.setColorWrite(true);
  75920. }
  75921. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75922. renderSubMesh(opaqueSubMeshes.data[index]);
  75923. }
  75924. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75925. renderSubMesh(alphaTestSubMeshes.data[index]);
  75926. }
  75927. if (transparentSubMeshes.length) {
  75928. // Sort sub meshes
  75929. for (index = 0; index < transparentSubMeshes.length; index++) {
  75930. var submesh = transparentSubMeshes.data[index];
  75931. var boundingInfo = submesh.getBoundingInfo();
  75932. if (boundingInfo && scene.activeCamera) {
  75933. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  75934. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  75935. }
  75936. }
  75937. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  75938. sortedArray.sort(function (a, b) {
  75939. // Alpha index first
  75940. if (a._alphaIndex > b._alphaIndex) {
  75941. return 1;
  75942. }
  75943. if (a._alphaIndex < b._alphaIndex) {
  75944. return -1;
  75945. }
  75946. // Then distance to camera
  75947. if (a._distanceToCamera < b._distanceToCamera) {
  75948. return 1;
  75949. }
  75950. if (a._distanceToCamera > b._distanceToCamera) {
  75951. return -1;
  75952. }
  75953. return 0;
  75954. });
  75955. // Render sub meshes
  75956. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  75957. for (index = 0; index < sortedArray.length; index++) {
  75958. renderSubMesh(sortedArray[index]);
  75959. }
  75960. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  75961. }
  75962. };
  75963. };
  75964. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  75965. var transform = scene.getTransformMatrix();
  75966. var meshPosition;
  75967. if (this.useCustomMeshPosition) {
  75968. meshPosition = this.customMeshPosition;
  75969. }
  75970. else if (this.attachedNode) {
  75971. meshPosition = this.attachedNode.position;
  75972. }
  75973. else {
  75974. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  75975. }
  75976. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  75977. this._screenCoordinates.x = pos.x / this._viewPort.width;
  75978. this._screenCoordinates.y = pos.y / this._viewPort.height;
  75979. if (this.invert)
  75980. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  75981. };
  75982. // Static methods
  75983. /**
  75984. * Creates a default mesh for the Volumeric Light Scattering post-process
  75985. * @param {string} The mesh name
  75986. * @param {BABYLON.Scene} The scene where to create the mesh
  75987. * @return {BABYLON.Mesh} the default mesh
  75988. */
  75989. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  75990. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  75991. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  75992. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  75993. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  75994. mesh.material = material;
  75995. return mesh;
  75996. };
  75997. __decorate([
  75998. BABYLON.serializeAsVector3()
  75999. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76000. __decorate([
  76001. BABYLON.serialize()
  76002. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76003. __decorate([
  76004. BABYLON.serialize()
  76005. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76006. __decorate([
  76007. BABYLON.serializeAsMeshReference()
  76008. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76009. __decorate([
  76010. BABYLON.serialize()
  76011. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76012. __decorate([
  76013. BABYLON.serialize()
  76014. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76015. __decorate([
  76016. BABYLON.serialize()
  76017. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76018. __decorate([
  76019. BABYLON.serialize()
  76020. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76021. __decorate([
  76022. BABYLON.serialize()
  76023. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76024. return VolumetricLightScatteringPostProcess;
  76025. }(BABYLON.PostProcess));
  76026. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76027. })(BABYLON || (BABYLON = {}));
  76028. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76029. //
  76030. // This post-process allows the modification of rendered colors by using
  76031. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76032. //
  76033. // The object needs to be provided an url to a texture containing the color
  76034. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76035. // Use an image editing software to tweak the LUT to match your needs.
  76036. //
  76037. // For an example of a color LUT, see here:
  76038. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76039. // For explanations on color grading, see here:
  76040. // http://udn.epicgames.com/Three/ColorGrading.html
  76041. //
  76042. var BABYLON;
  76043. (function (BABYLON) {
  76044. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76045. __extends(ColorCorrectionPostProcess, _super);
  76046. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76047. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76048. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76049. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76050. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76051. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76052. _this.onApply = function (effect) {
  76053. effect.setTexture("colorTable", _this._colorTableTexture);
  76054. };
  76055. return _this;
  76056. }
  76057. return ColorCorrectionPostProcess;
  76058. }(BABYLON.PostProcess));
  76059. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76060. })(BABYLON || (BABYLON = {}));
  76061. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76062. var BABYLON;
  76063. (function (BABYLON) {
  76064. var TonemappingOperator;
  76065. (function (TonemappingOperator) {
  76066. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76067. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76068. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76069. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76070. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76071. ;
  76072. var TonemapPostProcess = /** @class */ (function (_super) {
  76073. __extends(TonemapPostProcess, _super);
  76074. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76075. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76076. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76077. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76078. _this._operator = _operator;
  76079. _this.exposureAdjustment = exposureAdjustment;
  76080. var defines = "#define ";
  76081. if (_this._operator === TonemappingOperator.Hable)
  76082. defines += "HABLE_TONEMAPPING";
  76083. else if (_this._operator === TonemappingOperator.Reinhard)
  76084. defines += "REINHARD_TONEMAPPING";
  76085. else if (_this._operator === TonemappingOperator.HejiDawson)
  76086. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76087. else if (_this._operator === TonemappingOperator.Photographic)
  76088. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76089. //sadly a second call to create the effect.
  76090. _this.updateEffect(defines);
  76091. _this.onApply = function (effect) {
  76092. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76093. };
  76094. return _this;
  76095. }
  76096. return TonemapPostProcess;
  76097. }(BABYLON.PostProcess));
  76098. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76099. })(BABYLON || (BABYLON = {}));
  76100. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76101. var BABYLON;
  76102. (function (BABYLON) {
  76103. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76104. __extends(DisplayPassPostProcess, _super);
  76105. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76106. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76107. }
  76108. return DisplayPassPostProcess;
  76109. }(BABYLON.PostProcess));
  76110. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76111. })(BABYLON || (BABYLON = {}));
  76112. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76113. var BABYLON;
  76114. (function (BABYLON) {
  76115. var HighlightsPostProcess = /** @class */ (function (_super) {
  76116. __extends(HighlightsPostProcess, _super);
  76117. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76118. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76119. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76120. }
  76121. return HighlightsPostProcess;
  76122. }(BABYLON.PostProcess));
  76123. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76124. })(BABYLON || (BABYLON = {}));
  76125. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76126. var BABYLON;
  76127. (function (BABYLON) {
  76128. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76129. __extends(ImageProcessingPostProcess, _super);
  76130. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76131. if (camera === void 0) { camera = null; }
  76132. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76133. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76134. _this._fromLinearSpace = true;
  76135. /**
  76136. * Defines cache preventing GC.
  76137. */
  76138. _this._defines = {
  76139. IMAGEPROCESSING: false,
  76140. VIGNETTE: false,
  76141. VIGNETTEBLENDMODEMULTIPLY: false,
  76142. VIGNETTEBLENDMODEOPAQUE: false,
  76143. TONEMAPPING: false,
  76144. CONTRAST: false,
  76145. COLORCURVES: false,
  76146. COLORGRADING: false,
  76147. COLORGRADING3D: false,
  76148. FROMLINEARSPACE: false,
  76149. SAMPLER3DGREENDEPTH: false,
  76150. SAMPLER3DBGRMAP: false,
  76151. IMAGEPROCESSINGPOSTPROCESS: false,
  76152. EXPOSURE: false,
  76153. };
  76154. // Setup the configuration as forced by the constructor. This would then not force the
  76155. // scene materials output in linear space and let untouched the default forward pass.
  76156. if (imageProcessingConfiguration) {
  76157. imageProcessingConfiguration.applyByPostProcess = true;
  76158. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76159. // This will cause the shader to be compiled
  76160. _this.fromLinearSpace = false;
  76161. }
  76162. // Setup the default processing configuration to the scene.
  76163. else {
  76164. _this._attachImageProcessingConfiguration(null, true);
  76165. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76166. }
  76167. _this.onApply = function (effect) {
  76168. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76169. };
  76170. return _this;
  76171. }
  76172. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76173. /**
  76174. * Gets the image processing configuration used either in this material.
  76175. */
  76176. get: function () {
  76177. return this._imageProcessingConfiguration;
  76178. },
  76179. /**
  76180. * Sets the Default image processing configuration used either in the this material.
  76181. *
  76182. * If sets to null, the scene one is in use.
  76183. */
  76184. set: function (value) {
  76185. this._attachImageProcessingConfiguration(value);
  76186. },
  76187. enumerable: true,
  76188. configurable: true
  76189. });
  76190. /**
  76191. * Attaches a new image processing configuration to the PBR Material.
  76192. * @param configuration
  76193. */
  76194. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76195. var _this = this;
  76196. if (doNotBuild === void 0) { doNotBuild = false; }
  76197. if (configuration === this._imageProcessingConfiguration) {
  76198. return;
  76199. }
  76200. // Detaches observer.
  76201. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76202. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76203. }
  76204. // Pick the scene configuration if needed.
  76205. if (!configuration) {
  76206. var scene = null;
  76207. var engine = this.getEngine();
  76208. var camera = this.getCamera();
  76209. if (camera) {
  76210. scene = camera.getScene();
  76211. }
  76212. else if (engine && engine.scenes) {
  76213. var scenes = engine.scenes;
  76214. scene = scenes[scenes.length - 1];
  76215. }
  76216. else {
  76217. scene = BABYLON.Engine.LastCreatedScene;
  76218. }
  76219. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76220. }
  76221. else {
  76222. this._imageProcessingConfiguration = configuration;
  76223. }
  76224. // Attaches observer.
  76225. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76226. _this._updateParameters();
  76227. });
  76228. // Ensure the effect will be rebuilt.
  76229. if (!doNotBuild) {
  76230. this._updateParameters();
  76231. }
  76232. };
  76233. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76234. /**
  76235. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76236. */
  76237. get: function () {
  76238. return this.imageProcessingConfiguration.colorCurves;
  76239. },
  76240. /**
  76241. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76242. */
  76243. set: function (value) {
  76244. this.imageProcessingConfiguration.colorCurves = value;
  76245. },
  76246. enumerable: true,
  76247. configurable: true
  76248. });
  76249. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76250. /**
  76251. * Gets wether the color curves effect is enabled.
  76252. */
  76253. get: function () {
  76254. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76255. },
  76256. /**
  76257. * Sets wether the color curves effect is enabled.
  76258. */
  76259. set: function (value) {
  76260. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76261. },
  76262. enumerable: true,
  76263. configurable: true
  76264. });
  76265. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76266. /**
  76267. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76268. */
  76269. get: function () {
  76270. return this.imageProcessingConfiguration.colorGradingTexture;
  76271. },
  76272. /**
  76273. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76274. */
  76275. set: function (value) {
  76276. this.imageProcessingConfiguration.colorGradingTexture = value;
  76277. },
  76278. enumerable: true,
  76279. configurable: true
  76280. });
  76281. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76282. /**
  76283. * Gets wether the color grading effect is enabled.
  76284. */
  76285. get: function () {
  76286. return this.imageProcessingConfiguration.colorGradingEnabled;
  76287. },
  76288. /**
  76289. * Gets wether the color grading effect is enabled.
  76290. */
  76291. set: function (value) {
  76292. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76293. },
  76294. enumerable: true,
  76295. configurable: true
  76296. });
  76297. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76298. /**
  76299. * Gets exposure used in the effect.
  76300. */
  76301. get: function () {
  76302. return this.imageProcessingConfiguration.exposure;
  76303. },
  76304. /**
  76305. * Sets exposure used in the effect.
  76306. */
  76307. set: function (value) {
  76308. this.imageProcessingConfiguration.exposure = value;
  76309. },
  76310. enumerable: true,
  76311. configurable: true
  76312. });
  76313. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76314. /**
  76315. * Gets wether tonemapping is enabled or not.
  76316. */
  76317. get: function () {
  76318. return this._imageProcessingConfiguration.toneMappingEnabled;
  76319. },
  76320. /**
  76321. * Sets wether tonemapping is enabled or not
  76322. */
  76323. set: function (value) {
  76324. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76325. },
  76326. enumerable: true,
  76327. configurable: true
  76328. });
  76329. ;
  76330. ;
  76331. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76332. /**
  76333. * Gets contrast used in the effect.
  76334. */
  76335. get: function () {
  76336. return this.imageProcessingConfiguration.contrast;
  76337. },
  76338. /**
  76339. * Sets contrast used in the effect.
  76340. */
  76341. set: function (value) {
  76342. this.imageProcessingConfiguration.contrast = value;
  76343. },
  76344. enumerable: true,
  76345. configurable: true
  76346. });
  76347. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76348. /**
  76349. * Gets Vignette stretch size.
  76350. */
  76351. get: function () {
  76352. return this.imageProcessingConfiguration.vignetteStretch;
  76353. },
  76354. /**
  76355. * Sets Vignette stretch size.
  76356. */
  76357. set: function (value) {
  76358. this.imageProcessingConfiguration.vignetteStretch = value;
  76359. },
  76360. enumerable: true,
  76361. configurable: true
  76362. });
  76363. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76364. /**
  76365. * Gets Vignette centre X Offset.
  76366. */
  76367. get: function () {
  76368. return this.imageProcessingConfiguration.vignetteCentreX;
  76369. },
  76370. /**
  76371. * Sets Vignette centre X Offset.
  76372. */
  76373. set: function (value) {
  76374. this.imageProcessingConfiguration.vignetteCentreX = value;
  76375. },
  76376. enumerable: true,
  76377. configurable: true
  76378. });
  76379. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76380. /**
  76381. * Gets Vignette centre Y Offset.
  76382. */
  76383. get: function () {
  76384. return this.imageProcessingConfiguration.vignetteCentreY;
  76385. },
  76386. /**
  76387. * Sets Vignette centre Y Offset.
  76388. */
  76389. set: function (value) {
  76390. this.imageProcessingConfiguration.vignetteCentreY = value;
  76391. },
  76392. enumerable: true,
  76393. configurable: true
  76394. });
  76395. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76396. /**
  76397. * Gets Vignette weight or intensity of the vignette effect.
  76398. */
  76399. get: function () {
  76400. return this.imageProcessingConfiguration.vignetteWeight;
  76401. },
  76402. /**
  76403. * Sets Vignette weight or intensity of the vignette effect.
  76404. */
  76405. set: function (value) {
  76406. this.imageProcessingConfiguration.vignetteWeight = value;
  76407. },
  76408. enumerable: true,
  76409. configurable: true
  76410. });
  76411. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76412. /**
  76413. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76414. * if vignetteEnabled is set to true.
  76415. */
  76416. get: function () {
  76417. return this.imageProcessingConfiguration.vignetteColor;
  76418. },
  76419. /**
  76420. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76421. * if vignetteEnabled is set to true.
  76422. */
  76423. set: function (value) {
  76424. this.imageProcessingConfiguration.vignetteColor = value;
  76425. },
  76426. enumerable: true,
  76427. configurable: true
  76428. });
  76429. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76430. /**
  76431. * Gets Camera field of view used by the Vignette effect.
  76432. */
  76433. get: function () {
  76434. return this.imageProcessingConfiguration.vignetteCameraFov;
  76435. },
  76436. /**
  76437. * Sets Camera field of view used by the Vignette effect.
  76438. */
  76439. set: function (value) {
  76440. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76441. },
  76442. enumerable: true,
  76443. configurable: true
  76444. });
  76445. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76446. /**
  76447. * Gets the vignette blend mode allowing different kind of effect.
  76448. */
  76449. get: function () {
  76450. return this.imageProcessingConfiguration.vignetteBlendMode;
  76451. },
  76452. /**
  76453. * Sets the vignette blend mode allowing different kind of effect.
  76454. */
  76455. set: function (value) {
  76456. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76457. },
  76458. enumerable: true,
  76459. configurable: true
  76460. });
  76461. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76462. /**
  76463. * Gets wether the vignette effect is enabled.
  76464. */
  76465. get: function () {
  76466. return this.imageProcessingConfiguration.vignetteEnabled;
  76467. },
  76468. /**
  76469. * Sets wether the vignette effect is enabled.
  76470. */
  76471. set: function (value) {
  76472. this.imageProcessingConfiguration.vignetteEnabled = value;
  76473. },
  76474. enumerable: true,
  76475. configurable: true
  76476. });
  76477. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76478. /**
  76479. * Gets wether the input of the processing is in Gamma or Linear Space.
  76480. */
  76481. get: function () {
  76482. return this._fromLinearSpace;
  76483. },
  76484. /**
  76485. * Sets wether the input of the processing is in Gamma or Linear Space.
  76486. */
  76487. set: function (value) {
  76488. if (this._fromLinearSpace === value) {
  76489. return;
  76490. }
  76491. this._fromLinearSpace = value;
  76492. this._updateParameters();
  76493. },
  76494. enumerable: true,
  76495. configurable: true
  76496. });
  76497. ImageProcessingPostProcess.prototype.getClassName = function () {
  76498. return "ImageProcessingPostProcess";
  76499. };
  76500. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76501. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76502. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76503. var defines = "";
  76504. for (var define in this._defines) {
  76505. if (this._defines[define]) {
  76506. defines += "#define " + define + ";\r\n";
  76507. }
  76508. }
  76509. var samplers = ["textureSampler"];
  76510. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76511. var uniforms = ["scale"];
  76512. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76513. this.updateEffect(defines, uniforms, samplers);
  76514. };
  76515. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76516. _super.prototype.dispose.call(this, camera);
  76517. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76518. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76519. }
  76520. this.imageProcessingConfiguration.applyByPostProcess = false;
  76521. };
  76522. __decorate([
  76523. BABYLON.serialize()
  76524. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76525. return ImageProcessingPostProcess;
  76526. }(BABYLON.PostProcess));
  76527. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76528. })(BABYLON || (BABYLON = {}));
  76529. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76530. var BABYLON;
  76531. (function (BABYLON) {
  76532. /**
  76533. * Class used to store bone information
  76534. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  76535. */
  76536. var Bone = /** @class */ (function (_super) {
  76537. __extends(Bone, _super);
  76538. /**
  76539. * Create a new bone
  76540. * @param name defines the bone name
  76541. * @param skeleton defines the parent skeleton
  76542. * @param parentBone defines the parent (can be null if the bone is the root)
  76543. * @param localMatrix defines the local matrix
  76544. * @param restPose defines the rest pose matrix
  76545. * @param baseMatrix defines the base matrix
  76546. * @param index defines index of the bone in the hiearchy
  76547. */
  76548. function Bone(
  76549. /**
  76550. * defines the bone name
  76551. */
  76552. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76553. if (parentBone === void 0) { parentBone = null; }
  76554. if (localMatrix === void 0) { localMatrix = null; }
  76555. if (restPose === void 0) { restPose = null; }
  76556. if (baseMatrix === void 0) { baseMatrix = null; }
  76557. if (index === void 0) { index = null; }
  76558. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76559. _this.name = name;
  76560. /**
  76561. * Gets the list of child bones
  76562. */
  76563. _this.children = new Array();
  76564. /** Gets the animations associated with this bone */
  76565. _this.animations = new Array();
  76566. /**
  76567. * @ignore Internal only
  76568. * Set this value to map this bone to a different index in the transform matrices
  76569. * Set this value to -1 to exclude the bone from the transform matrices
  76570. */
  76571. _this._index = null;
  76572. _this._absoluteTransform = new BABYLON.Matrix();
  76573. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76574. _this._scalingDeterminant = 1;
  76575. _this._worldTransform = new BABYLON.Matrix();
  76576. _this._needToDecompose = true;
  76577. _this._needToCompose = false;
  76578. _this._skeleton = skeleton;
  76579. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76580. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76581. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76582. _this._index = index;
  76583. skeleton.bones.push(_this);
  76584. _this.setParent(parentBone, false);
  76585. if (baseMatrix || localMatrix) {
  76586. _this._updateDifferenceMatrix();
  76587. }
  76588. return _this;
  76589. }
  76590. Object.defineProperty(Bone.prototype, "_matrix", {
  76591. /** @ignore */
  76592. get: function () {
  76593. this._compose();
  76594. return this._localMatrix;
  76595. },
  76596. /** @ignore */
  76597. set: function (value) {
  76598. this._localMatrix.copyFrom(value);
  76599. this._needToDecompose = true;
  76600. },
  76601. enumerable: true,
  76602. configurable: true
  76603. });
  76604. // Members
  76605. /**
  76606. * Gets the parent skeleton
  76607. * @returns a skeleton
  76608. */
  76609. Bone.prototype.getSkeleton = function () {
  76610. return this._skeleton;
  76611. };
  76612. /**
  76613. * Gets parent bone
  76614. * @returns a bone or null if the bone is the root of the bone hierarchy
  76615. */
  76616. Bone.prototype.getParent = function () {
  76617. return this._parent;
  76618. };
  76619. /**
  76620. * Sets the parent bone
  76621. * @param parent defines the parent (can be null if the bone is the root)
  76622. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76623. */
  76624. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76625. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76626. if (this._parent === parent) {
  76627. return;
  76628. }
  76629. if (this._parent) {
  76630. var index = this._parent.children.indexOf(this);
  76631. if (index !== -1) {
  76632. this._parent.children.splice(index, 1);
  76633. }
  76634. }
  76635. this._parent = parent;
  76636. if (this._parent) {
  76637. this._parent.children.push(this);
  76638. }
  76639. if (updateDifferenceMatrix) {
  76640. this._updateDifferenceMatrix();
  76641. }
  76642. this.markAsDirty();
  76643. };
  76644. /**
  76645. * Gets the local matrix
  76646. * @returns a matrix
  76647. */
  76648. Bone.prototype.getLocalMatrix = function () {
  76649. this._compose();
  76650. return this._localMatrix;
  76651. };
  76652. /**
  76653. * Gets the base matrix (initial matrix which remains unchanged)
  76654. * @returns a matrix
  76655. */
  76656. Bone.prototype.getBaseMatrix = function () {
  76657. return this._baseMatrix;
  76658. };
  76659. /**
  76660. * Gets the rest pose matrix
  76661. * @returns a matrix
  76662. */
  76663. Bone.prototype.getRestPose = function () {
  76664. return this._restPose;
  76665. };
  76666. /**
  76667. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  76668. */
  76669. Bone.prototype.getWorldMatrix = function () {
  76670. return this._worldTransform;
  76671. };
  76672. /**
  76673. * Sets the local matrix to rest pose matrix
  76674. */
  76675. Bone.prototype.returnToRest = function () {
  76676. this.updateMatrix(this._restPose.clone());
  76677. };
  76678. /**
  76679. * Gets the inverse of the absolute transform matrix.
  76680. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  76681. * @returns a matrix
  76682. */
  76683. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76684. return this._invertedAbsoluteTransform;
  76685. };
  76686. /**
  76687. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  76688. * @returns a matrix
  76689. */
  76690. Bone.prototype.getAbsoluteTransform = function () {
  76691. return this._absoluteTransform;
  76692. };
  76693. Object.defineProperty(Bone.prototype, "position", {
  76694. // Properties (matches AbstractMesh properties)
  76695. /** Gets or sets current position (in local space) */
  76696. get: function () {
  76697. this._decompose();
  76698. return this._localPosition;
  76699. },
  76700. set: function (newPosition) {
  76701. this._decompose();
  76702. this._localPosition.copyFrom(newPosition);
  76703. this._markAsDirtyAndCompose();
  76704. },
  76705. enumerable: true,
  76706. configurable: true
  76707. });
  76708. Object.defineProperty(Bone.prototype, "rotation", {
  76709. /** Gets or sets current rotation (in local space) */
  76710. get: function () {
  76711. return this.getRotation();
  76712. },
  76713. set: function (newRotation) {
  76714. this.setRotation(newRotation);
  76715. },
  76716. enumerable: true,
  76717. configurable: true
  76718. });
  76719. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76720. /** Gets or sets current rotation quaternion (in local space) */
  76721. get: function () {
  76722. this._decompose();
  76723. return this._localRotation;
  76724. },
  76725. set: function (newRotation) {
  76726. this.setRotationQuaternion(newRotation);
  76727. },
  76728. enumerable: true,
  76729. configurable: true
  76730. });
  76731. Object.defineProperty(Bone.prototype, "scaling", {
  76732. /** Gets or sets current scaling (in local space) */
  76733. get: function () {
  76734. return this.getScale();
  76735. },
  76736. set: function (newScaling) {
  76737. this.setScale(newScaling);
  76738. },
  76739. enumerable: true,
  76740. configurable: true
  76741. });
  76742. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76743. /**
  76744. * Gets the animation properties override
  76745. */
  76746. get: function () {
  76747. return this._skeleton.animationPropertiesOverride;
  76748. },
  76749. enumerable: true,
  76750. configurable: true
  76751. });
  76752. // Methods
  76753. Bone.prototype._decompose = function () {
  76754. if (!this._needToDecompose) {
  76755. return;
  76756. }
  76757. this._needToDecompose = false;
  76758. if (!this._localScaling) {
  76759. this._localScaling = BABYLON.Vector3.Zero();
  76760. this._localRotation = BABYLON.Quaternion.Zero();
  76761. this._localPosition = BABYLON.Vector3.Zero();
  76762. }
  76763. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  76764. };
  76765. Bone.prototype._compose = function () {
  76766. if (!this._needToCompose) {
  76767. return;
  76768. }
  76769. this._needToCompose = false;
  76770. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  76771. };
  76772. /**
  76773. * Update the base and local matrices
  76774. * @param matrix defines the new base or local matrix
  76775. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76776. * @param updateLocalMatrix defines if the local matrix should be updated
  76777. */
  76778. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  76779. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76780. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  76781. this._baseMatrix.copyFrom(matrix);
  76782. if (updateDifferenceMatrix) {
  76783. this._updateDifferenceMatrix();
  76784. }
  76785. if (updateLocalMatrix) {
  76786. this._localMatrix.copyFrom(matrix);
  76787. this._markAsDirtyAndDecompose();
  76788. }
  76789. else {
  76790. this.markAsDirty();
  76791. }
  76792. };
  76793. /** @ignore */
  76794. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  76795. if (updateChildren === void 0) { updateChildren = true; }
  76796. if (!rootMatrix) {
  76797. rootMatrix = this._baseMatrix;
  76798. }
  76799. if (this._parent) {
  76800. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76801. }
  76802. else {
  76803. this._absoluteTransform.copyFrom(rootMatrix);
  76804. }
  76805. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76806. if (updateChildren) {
  76807. for (var index = 0; index < this.children.length; index++) {
  76808. this.children[index]._updateDifferenceMatrix();
  76809. }
  76810. }
  76811. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76812. };
  76813. /**
  76814. * Flag the bone as dirty (Forcing it to update everything)
  76815. */
  76816. Bone.prototype.markAsDirty = function () {
  76817. this._currentRenderId++;
  76818. this._childRenderId++;
  76819. this._skeleton._markAsDirty();
  76820. };
  76821. Bone.prototype._markAsDirtyAndCompose = function () {
  76822. this.markAsDirty();
  76823. this._needToCompose = true;
  76824. };
  76825. Bone.prototype._markAsDirtyAndDecompose = function () {
  76826. this.markAsDirty();
  76827. this._needToDecompose = true;
  76828. };
  76829. /**
  76830. * Copy an animation range from another bone
  76831. * @param source defines the source bone
  76832. * @param rangeName defines the range name to copy
  76833. * @param frameOffset defines the frame offset
  76834. * @param rescaleAsRequired defines if rescaling must be applied if required
  76835. * @param skelDimensionsRatio defines the scaling ratio
  76836. * @returns true if operation was successful
  76837. */
  76838. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76839. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76840. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76841. // all animation may be coming from a library skeleton, so may need to create animation
  76842. if (this.animations.length === 0) {
  76843. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  76844. this.animations[0].setKeys([]);
  76845. }
  76846. // get animation info / verify there is such a range from the source bone
  76847. var sourceRange = source.animations[0].getRange(rangeName);
  76848. if (!sourceRange) {
  76849. return false;
  76850. }
  76851. var from = sourceRange.from;
  76852. var to = sourceRange.to;
  76853. var sourceKeys = source.animations[0].getKeys();
  76854. // rescaling prep
  76855. var sourceBoneLength = source.length;
  76856. var sourceParent = source.getParent();
  76857. var parent = this.getParent();
  76858. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  76859. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  76860. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  76861. var destKeys = this.animations[0].getKeys();
  76862. // loop vars declaration
  76863. var orig;
  76864. var origTranslation;
  76865. var mat;
  76866. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  76867. orig = sourceKeys[key];
  76868. if (orig.frame >= from && orig.frame <= to) {
  76869. if (rescaleAsRequired) {
  76870. mat = orig.value.clone();
  76871. // scale based on parent ratio, when bone has parent
  76872. if (parentScalingReqd) {
  76873. origTranslation = mat.getTranslation();
  76874. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  76875. // scale based on skeleton dimension ratio when root bone, and value is passed
  76876. }
  76877. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  76878. origTranslation = mat.getTranslation();
  76879. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  76880. // use original when root bone, and no data for skelDimensionsRatio
  76881. }
  76882. else {
  76883. mat = orig.value;
  76884. }
  76885. }
  76886. else {
  76887. mat = orig.value;
  76888. }
  76889. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  76890. }
  76891. }
  76892. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  76893. return true;
  76894. };
  76895. /**
  76896. * Translate the bone in local or world space
  76897. * @param vec The amount to translate the bone
  76898. * @param space The space that the translation is in
  76899. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76900. */
  76901. Bone.prototype.translate = function (vec, space, mesh) {
  76902. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76903. var lm = this.getLocalMatrix();
  76904. if (space == BABYLON.Space.LOCAL) {
  76905. lm.m[12] += vec.x;
  76906. lm.m[13] += vec.y;
  76907. lm.m[14] += vec.z;
  76908. }
  76909. else {
  76910. var wm = null;
  76911. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76912. if (mesh) {
  76913. wm = mesh.getWorldMatrix();
  76914. }
  76915. this._skeleton.computeAbsoluteTransforms();
  76916. var tmat = Bone._tmpMats[0];
  76917. var tvec = Bone._tmpVecs[0];
  76918. if (this._parent) {
  76919. if (mesh && wm) {
  76920. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76921. tmat.multiplyToRef(wm, tmat);
  76922. }
  76923. else {
  76924. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76925. }
  76926. }
  76927. tmat.m[12] = 0;
  76928. tmat.m[13] = 0;
  76929. tmat.m[14] = 0;
  76930. tmat.invert();
  76931. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  76932. lm.m[12] += tvec.x;
  76933. lm.m[13] += tvec.y;
  76934. lm.m[14] += tvec.z;
  76935. }
  76936. this._markAsDirtyAndDecompose();
  76937. };
  76938. /**
  76939. * Set the postion of the bone in local or world space
  76940. * @param position The position to set the bone
  76941. * @param space The space that the position is in
  76942. * @param mesh The mesh that this bone is attached to. This is only used in world space
  76943. */
  76944. Bone.prototype.setPosition = function (position, space, mesh) {
  76945. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  76946. var lm = this.getLocalMatrix();
  76947. if (space == BABYLON.Space.LOCAL) {
  76948. lm.m[12] = position.x;
  76949. lm.m[13] = position.y;
  76950. lm.m[14] = position.z;
  76951. }
  76952. else {
  76953. var wm = null;
  76954. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  76955. if (mesh) {
  76956. wm = mesh.getWorldMatrix();
  76957. }
  76958. this._skeleton.computeAbsoluteTransforms();
  76959. var tmat = Bone._tmpMats[0];
  76960. var vec = Bone._tmpVecs[0];
  76961. if (this._parent) {
  76962. if (mesh && wm) {
  76963. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76964. tmat.multiplyToRef(wm, tmat);
  76965. }
  76966. else {
  76967. tmat.copyFrom(this._parent.getAbsoluteTransform());
  76968. }
  76969. }
  76970. tmat.invert();
  76971. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  76972. lm.m[12] = vec.x;
  76973. lm.m[13] = vec.y;
  76974. lm.m[14] = vec.z;
  76975. }
  76976. this._markAsDirtyAndDecompose();
  76977. };
  76978. /**
  76979. * Set the absolute position of the bone (world space)
  76980. * @param position The position to set the bone
  76981. * @param mesh The mesh that this bone is attached to
  76982. */
  76983. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  76984. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  76985. };
  76986. /**
  76987. * Scale the bone on the x, y and z axes (in local space)
  76988. * @param x The amount to scale the bone on the x axis
  76989. * @param y The amount to scale the bone on the y axis
  76990. * @param z The amount to scale the bone on the z axis
  76991. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  76992. */
  76993. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  76994. if (scaleChildren === void 0) { scaleChildren = false; }
  76995. var locMat = this.getLocalMatrix();
  76996. // Apply new scaling on top of current local matrix
  76997. var scaleMat = Bone._tmpMats[0];
  76998. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  76999. scaleMat.multiplyToRef(locMat, locMat);
  77000. // Invert scaling matrix and apply the inverse to all children
  77001. scaleMat.invert();
  77002. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77003. var child = _a[_i];
  77004. var cm = child.getLocalMatrix();
  77005. cm.multiplyToRef(scaleMat, cm);
  77006. cm.m[12] *= x;
  77007. cm.m[13] *= y;
  77008. cm.m[14] *= z;
  77009. child._markAsDirtyAndDecompose();
  77010. }
  77011. this._markAsDirtyAndDecompose();
  77012. if (scaleChildren) {
  77013. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77014. var child = _c[_b];
  77015. child.scale(x, y, z, scaleChildren);
  77016. }
  77017. }
  77018. };
  77019. /**
  77020. * Set the bone scaling in local space
  77021. * @param scale defines the scaling vector
  77022. */
  77023. Bone.prototype.setScale = function (scale) {
  77024. this._decompose();
  77025. this._localScaling.copyFrom(scale);
  77026. this._markAsDirtyAndCompose();
  77027. };
  77028. /**
  77029. * Gets the current scaling in local space
  77030. * @returns the current scaling vector
  77031. */
  77032. Bone.prototype.getScale = function () {
  77033. this._decompose();
  77034. return this._localScaling;
  77035. };
  77036. /**
  77037. * Gets the current scaling in local space and stores it in a target vector
  77038. * @param result defines the target vector
  77039. */
  77040. Bone.prototype.getScaleToRef = function (result) {
  77041. this._decompose();
  77042. result.copyFrom(this._localScaling);
  77043. };
  77044. /**
  77045. * Set the yaw, pitch, and roll of the bone in local or world space
  77046. * @param yaw The rotation of the bone on the y axis
  77047. * @param pitch The rotation of the bone on the x axis
  77048. * @param roll The rotation of the bone on the z axis
  77049. * @param space The space that the axes of rotation are in
  77050. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77051. */
  77052. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77053. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77054. if (space === BABYLON.Space.LOCAL) {
  77055. var quat = Bone._tmpQuat;
  77056. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77057. this.setRotationQuaternion(quat, space, mesh);
  77058. return;
  77059. }
  77060. var rotMatInv = Bone._tmpMats[0];
  77061. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77062. return;
  77063. }
  77064. var rotMat = Bone._tmpMats[1];
  77065. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77066. rotMatInv.multiplyToRef(rotMat, rotMat);
  77067. this._rotateWithMatrix(rotMat, space, mesh);
  77068. };
  77069. /**
  77070. * Add a rotation to the bone on an axis in local or world space
  77071. * @param axis The axis to rotate the bone on
  77072. * @param amount The amount to rotate the bone
  77073. * @param space The space that the axis is in
  77074. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77075. */
  77076. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77077. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77078. var rmat = Bone._tmpMats[0];
  77079. rmat.m[12] = 0;
  77080. rmat.m[13] = 0;
  77081. rmat.m[14] = 0;
  77082. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77083. this._rotateWithMatrix(rmat, space, mesh);
  77084. };
  77085. /**
  77086. * Set the rotation of the bone to a particular axis angle in local or world space
  77087. * @param axis The axis to rotate the bone on
  77088. * @param angle The angle that the bone should be rotated to
  77089. * @param space The space that the axis is in
  77090. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77091. */
  77092. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77093. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77094. if (space === BABYLON.Space.LOCAL) {
  77095. var quat = Bone._tmpQuat;
  77096. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77097. this.setRotationQuaternion(quat, space, mesh);
  77098. return;
  77099. }
  77100. var rotMatInv = Bone._tmpMats[0];
  77101. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77102. return;
  77103. }
  77104. var rotMat = Bone._tmpMats[1];
  77105. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77106. rotMatInv.multiplyToRef(rotMat, rotMat);
  77107. this._rotateWithMatrix(rotMat, space, mesh);
  77108. };
  77109. /**
  77110. * Set the euler rotation of the bone in local of world space
  77111. * @param rotation The euler rotation that the bone should be set to
  77112. * @param space The space that the rotation is in
  77113. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77114. */
  77115. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77116. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77117. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77118. };
  77119. /**
  77120. * Set the quaternion rotation of the bone in local of world space
  77121. * @param quat The quaternion rotation that the bone should be set to
  77122. * @param space The space that the rotation is in
  77123. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77124. */
  77125. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77127. if (space === BABYLON.Space.LOCAL) {
  77128. this._decompose();
  77129. this._localRotation.copyFrom(quat);
  77130. this._markAsDirtyAndCompose();
  77131. return;
  77132. }
  77133. var rotMatInv = Bone._tmpMats[0];
  77134. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77135. return;
  77136. }
  77137. var rotMat = Bone._tmpMats[1];
  77138. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77139. rotMatInv.multiplyToRef(rotMat, rotMat);
  77140. this._rotateWithMatrix(rotMat, space, mesh);
  77141. };
  77142. /**
  77143. * Set the rotation matrix of the bone in local of world space
  77144. * @param rotMat The rotation matrix that the bone should be set to
  77145. * @param space The space that the rotation is in
  77146. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77147. */
  77148. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77149. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77150. if (space === BABYLON.Space.LOCAL) {
  77151. var quat = Bone._tmpQuat;
  77152. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77153. this.setRotationQuaternion(quat, space, mesh);
  77154. return;
  77155. }
  77156. var rotMatInv = Bone._tmpMats[0];
  77157. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77158. return;
  77159. }
  77160. var rotMat2 = Bone._tmpMats[1];
  77161. rotMat2.copyFrom(rotMat);
  77162. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77163. this._rotateWithMatrix(rotMat2, space, mesh);
  77164. };
  77165. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77166. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77167. var lmat = this.getLocalMatrix();
  77168. var lx = lmat.m[12];
  77169. var ly = lmat.m[13];
  77170. var lz = lmat.m[14];
  77171. var parent = this.getParent();
  77172. var parentScale = Bone._tmpMats[3];
  77173. var parentScaleInv = Bone._tmpMats[4];
  77174. if (parent && space == BABYLON.Space.WORLD) {
  77175. if (mesh) {
  77176. parentScale.copyFrom(mesh.getWorldMatrix());
  77177. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77178. }
  77179. else {
  77180. parentScale.copyFrom(parent.getAbsoluteTransform());
  77181. }
  77182. parentScaleInv.copyFrom(parentScale);
  77183. parentScaleInv.invert();
  77184. lmat.multiplyToRef(parentScale, lmat);
  77185. lmat.multiplyToRef(rmat, lmat);
  77186. lmat.multiplyToRef(parentScaleInv, lmat);
  77187. }
  77188. else {
  77189. if (space == BABYLON.Space.WORLD && mesh) {
  77190. parentScale.copyFrom(mesh.getWorldMatrix());
  77191. parentScaleInv.copyFrom(parentScale);
  77192. parentScaleInv.invert();
  77193. lmat.multiplyToRef(parentScale, lmat);
  77194. lmat.multiplyToRef(rmat, lmat);
  77195. lmat.multiplyToRef(parentScaleInv, lmat);
  77196. }
  77197. else {
  77198. lmat.multiplyToRef(rmat, lmat);
  77199. }
  77200. }
  77201. lmat.m[12] = lx;
  77202. lmat.m[13] = ly;
  77203. lmat.m[14] = lz;
  77204. this.computeAbsoluteTransforms();
  77205. this._markAsDirtyAndDecompose();
  77206. };
  77207. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77208. var scaleMatrix = Bone._tmpMats[2];
  77209. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77210. if (mesh) {
  77211. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77212. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77213. }
  77214. rotMatInv.invert();
  77215. if (isNaN(rotMatInv.m[0])) {
  77216. // Matrix failed to invert.
  77217. // This can happen if scale is zero for example.
  77218. return false;
  77219. }
  77220. scaleMatrix.m[0] *= this._scalingDeterminant;
  77221. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77222. return true;
  77223. };
  77224. /**
  77225. * Get the position of the bone in local or world space
  77226. * @param space The space that the returned position is in
  77227. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77228. * @returns The position of the bone
  77229. */
  77230. Bone.prototype.getPosition = function (space, mesh) {
  77231. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77232. if (mesh === void 0) { mesh = null; }
  77233. var pos = BABYLON.Vector3.Zero();
  77234. this.getPositionToRef(space, mesh, pos);
  77235. return pos;
  77236. };
  77237. /**
  77238. * Copy the position of the bone to a vector3 in local or world space
  77239. * @param space The space that the returned position is in
  77240. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77241. * @param result The vector3 to copy the position to
  77242. */
  77243. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77244. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77245. if (space == BABYLON.Space.LOCAL) {
  77246. var lm = this.getLocalMatrix();
  77247. result.x = lm.m[12];
  77248. result.y = lm.m[13];
  77249. result.z = lm.m[14];
  77250. }
  77251. else {
  77252. var wm = null;
  77253. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77254. if (mesh) {
  77255. wm = mesh.getWorldMatrix();
  77256. }
  77257. this._skeleton.computeAbsoluteTransforms();
  77258. var tmat = Bone._tmpMats[0];
  77259. if (mesh && wm) {
  77260. tmat.copyFrom(this.getAbsoluteTransform());
  77261. tmat.multiplyToRef(wm, tmat);
  77262. }
  77263. else {
  77264. tmat = this.getAbsoluteTransform();
  77265. }
  77266. result.x = tmat.m[12];
  77267. result.y = tmat.m[13];
  77268. result.z = tmat.m[14];
  77269. }
  77270. };
  77271. /**
  77272. * Get the absolute position of the bone (world space)
  77273. * @param mesh The mesh that this bone is attached to
  77274. * @returns The absolute position of the bone
  77275. */
  77276. Bone.prototype.getAbsolutePosition = function (mesh) {
  77277. if (mesh === void 0) { mesh = null; }
  77278. var pos = BABYLON.Vector3.Zero();
  77279. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77280. return pos;
  77281. };
  77282. /**
  77283. * Copy the absolute position of the bone (world space) to the result param
  77284. * @param mesh The mesh that this bone is attached to
  77285. * @param result The vector3 to copy the absolute position to
  77286. */
  77287. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77288. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77289. };
  77290. /**
  77291. * Compute the absolute transforms of this bone and its children
  77292. */
  77293. Bone.prototype.computeAbsoluteTransforms = function () {
  77294. this._compose();
  77295. if (this._parent) {
  77296. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77297. }
  77298. else {
  77299. this._absoluteTransform.copyFrom(this._localMatrix);
  77300. var poseMatrix = this._skeleton.getPoseMatrix();
  77301. if (poseMatrix) {
  77302. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77303. }
  77304. }
  77305. var children = this.children;
  77306. var len = children.length;
  77307. for (var i = 0; i < len; i++) {
  77308. children[i].computeAbsoluteTransforms();
  77309. }
  77310. };
  77311. /**
  77312. * Get the world direction from an axis that is in the local space of the bone
  77313. * @param localAxis The local direction that is used to compute the world direction
  77314. * @param mesh The mesh that this bone is attached to
  77315. * @returns The world direction
  77316. */
  77317. Bone.prototype.getDirection = function (localAxis, mesh) {
  77318. if (mesh === void 0) { mesh = null; }
  77319. var result = BABYLON.Vector3.Zero();
  77320. this.getDirectionToRef(localAxis, mesh, result);
  77321. return result;
  77322. };
  77323. /**
  77324. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77325. * @param localAxis The local direction that is used to compute the world direction
  77326. * @param mesh The mesh that this bone is attached to
  77327. * @param result The vector3 that the world direction will be copied to
  77328. */
  77329. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77330. if (mesh === void 0) { mesh = null; }
  77331. var wm = null;
  77332. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77333. if (mesh) {
  77334. wm = mesh.getWorldMatrix();
  77335. }
  77336. this._skeleton.computeAbsoluteTransforms();
  77337. var mat = Bone._tmpMats[0];
  77338. mat.copyFrom(this.getAbsoluteTransform());
  77339. if (mesh && wm) {
  77340. mat.multiplyToRef(wm, mat);
  77341. }
  77342. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77343. result.normalize();
  77344. };
  77345. /**
  77346. * Get the euler rotation of the bone in local or world space
  77347. * @param space The space that the rotation should be in
  77348. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77349. * @returns The euler rotation
  77350. */
  77351. Bone.prototype.getRotation = function (space, mesh) {
  77352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77353. if (mesh === void 0) { mesh = null; }
  77354. var result = BABYLON.Vector3.Zero();
  77355. this.getRotationToRef(space, mesh, result);
  77356. return result;
  77357. };
  77358. /**
  77359. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77360. * @param space The space that the rotation should be in
  77361. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77362. * @param result The vector3 that the rotation should be copied to
  77363. */
  77364. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77365. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77366. if (mesh === void 0) { mesh = null; }
  77367. var quat = Bone._tmpQuat;
  77368. this.getRotationQuaternionToRef(space, mesh, quat);
  77369. quat.toEulerAnglesToRef(result);
  77370. };
  77371. /**
  77372. * Get the quaternion rotation of the bone in either local or world space
  77373. * @param space The space that the rotation should be in
  77374. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77375. * @returns The quaternion rotation
  77376. */
  77377. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77378. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77379. if (mesh === void 0) { mesh = null; }
  77380. var result = BABYLON.Quaternion.Identity();
  77381. this.getRotationQuaternionToRef(space, mesh, result);
  77382. return result;
  77383. };
  77384. /**
  77385. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77386. * @param space The space that the rotation should be in
  77387. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77388. * @param result The quaternion that the rotation should be copied to
  77389. */
  77390. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  77391. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77392. if (mesh === void 0) { mesh = null; }
  77393. if (space == BABYLON.Space.LOCAL) {
  77394. this._decompose();
  77395. result.copyFrom(this._localRotation);
  77396. }
  77397. else {
  77398. var mat = Bone._tmpMats[0];
  77399. var amat = this.getAbsoluteTransform();
  77400. if (mesh) {
  77401. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77402. }
  77403. else {
  77404. mat.copyFrom(amat);
  77405. }
  77406. mat.m[0] *= this._scalingDeterminant;
  77407. mat.m[1] *= this._scalingDeterminant;
  77408. mat.m[2] *= this._scalingDeterminant;
  77409. mat.decompose(undefined, result, undefined);
  77410. }
  77411. };
  77412. /**
  77413. * Get the rotation matrix of the bone in local or world space
  77414. * @param space The space that the rotation should be in
  77415. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77416. * @returns The rotation matrix
  77417. */
  77418. Bone.prototype.getRotationMatrix = function (space, mesh) {
  77419. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77420. var result = BABYLON.Matrix.Identity();
  77421. this.getRotationMatrixToRef(space, mesh, result);
  77422. return result;
  77423. };
  77424. /**
  77425. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  77426. * @param space The space that the rotation should be in
  77427. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77428. * @param result The quaternion that the rotation should be copied to
  77429. */
  77430. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77431. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77432. if (space == BABYLON.Space.LOCAL) {
  77433. this.getLocalMatrix().getRotationMatrixToRef(result);
  77434. }
  77435. else {
  77436. var mat = Bone._tmpMats[0];
  77437. var amat = this.getAbsoluteTransform();
  77438. if (mesh) {
  77439. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77440. }
  77441. else {
  77442. mat.copyFrom(amat);
  77443. }
  77444. mat.m[0] *= this._scalingDeterminant;
  77445. mat.m[1] *= this._scalingDeterminant;
  77446. mat.m[2] *= this._scalingDeterminant;
  77447. mat.getRotationMatrixToRef(result);
  77448. }
  77449. };
  77450. /**
  77451. * Get the world position of a point that is in the local space of the bone
  77452. * @param position The local position
  77453. * @param mesh The mesh that this bone is attached to
  77454. * @returns The world position
  77455. */
  77456. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77457. if (mesh === void 0) { mesh = null; }
  77458. var result = BABYLON.Vector3.Zero();
  77459. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77460. return result;
  77461. };
  77462. /**
  77463. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  77464. * @param position The local position
  77465. * @param mesh The mesh that this bone is attached to
  77466. * @param result The vector3 that the world position should be copied to
  77467. */
  77468. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77469. if (mesh === void 0) { mesh = null; }
  77470. var wm = null;
  77471. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77472. if (mesh) {
  77473. wm = mesh.getWorldMatrix();
  77474. }
  77475. this._skeleton.computeAbsoluteTransforms();
  77476. var tmat = Bone._tmpMats[0];
  77477. if (mesh && wm) {
  77478. tmat.copyFrom(this.getAbsoluteTransform());
  77479. tmat.multiplyToRef(wm, tmat);
  77480. }
  77481. else {
  77482. tmat = this.getAbsoluteTransform();
  77483. }
  77484. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77485. };
  77486. /**
  77487. * Get the local position of a point that is in world space
  77488. * @param position The world position
  77489. * @param mesh The mesh that this bone is attached to
  77490. * @returns The local position
  77491. */
  77492. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77493. if (mesh === void 0) { mesh = null; }
  77494. var result = BABYLON.Vector3.Zero();
  77495. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77496. return result;
  77497. };
  77498. /**
  77499. * Get the local position of a point that is in world space and copy it to the result param
  77500. * @param position The world position
  77501. * @param mesh The mesh that this bone is attached to
  77502. * @param result The vector3 that the local position should be copied to
  77503. */
  77504. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77505. if (mesh === void 0) { mesh = null; }
  77506. var wm = null;
  77507. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77508. if (mesh) {
  77509. wm = mesh.getWorldMatrix();
  77510. }
  77511. this._skeleton.computeAbsoluteTransforms();
  77512. var tmat = Bone._tmpMats[0];
  77513. tmat.copyFrom(this.getAbsoluteTransform());
  77514. if (mesh && wm) {
  77515. tmat.multiplyToRef(wm, tmat);
  77516. }
  77517. tmat.invert();
  77518. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77519. };
  77520. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77521. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77522. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77523. return Bone;
  77524. }(BABYLON.Node));
  77525. BABYLON.Bone = Bone;
  77526. })(BABYLON || (BABYLON = {}));
  77527. //# sourceMappingURL=babylon.bone.js.map
  77528. var BABYLON;
  77529. (function (BABYLON) {
  77530. /**
  77531. * Class used to apply inverse kinematics to bones
  77532. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  77533. */
  77534. var BoneIKController = /** @class */ (function () {
  77535. /**
  77536. * Creates a new BoneIKController
  77537. * @param mesh defines the mesh to control
  77538. * @param bone defines the bone to control
  77539. * @param options defines options to set up the controller
  77540. */
  77541. function BoneIKController(mesh, bone, options) {
  77542. /**
  77543. * Gets or sets the target position
  77544. */
  77545. this.targetPosition = BABYLON.Vector3.Zero();
  77546. /**
  77547. * Gets or sets the pole target position
  77548. */
  77549. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77550. /**
  77551. * Gets or sets the pole target local offset
  77552. */
  77553. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77554. /**
  77555. * Gets or sets the pole angle
  77556. */
  77557. this.poleAngle = 0;
  77558. /**
  77559. * 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)
  77560. */
  77561. this.slerpAmount = 1;
  77562. this._bone1Quat = BABYLON.Quaternion.Identity();
  77563. this._bone1Mat = BABYLON.Matrix.Identity();
  77564. this._bone2Ang = Math.PI;
  77565. this._maxAngle = Math.PI;
  77566. this._rightHandedSystem = false;
  77567. this._bendAxis = BABYLON.Vector3.Right();
  77568. this._slerping = false;
  77569. this._adjustRoll = 0;
  77570. this._bone2 = bone;
  77571. this._bone1 = bone.getParent();
  77572. if (!this._bone1) {
  77573. return;
  77574. }
  77575. this.mesh = mesh;
  77576. var bonePos = bone.getPosition();
  77577. if (bone.getAbsoluteTransform().determinant() > 0) {
  77578. this._rightHandedSystem = true;
  77579. this._bendAxis.x = 0;
  77580. this._bendAxis.y = 0;
  77581. this._bendAxis.z = -1;
  77582. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77583. this._adjustRoll = Math.PI * .5;
  77584. this._bendAxis.z = 1;
  77585. }
  77586. }
  77587. if (this._bone1.length) {
  77588. var boneScale1 = this._bone1.getScale();
  77589. var boneScale2 = this._bone2.getScale();
  77590. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77591. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77592. }
  77593. else if (this._bone1.children[0]) {
  77594. mesh.computeWorldMatrix(true);
  77595. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77596. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77597. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77598. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77599. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77600. }
  77601. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77602. this.maxAngle = Math.PI;
  77603. if (options) {
  77604. if (options.targetMesh) {
  77605. this.targetMesh = options.targetMesh;
  77606. this.targetMesh.computeWorldMatrix(true);
  77607. }
  77608. if (options.poleTargetMesh) {
  77609. this.poleTargetMesh = options.poleTargetMesh;
  77610. this.poleTargetMesh.computeWorldMatrix(true);
  77611. }
  77612. else if (options.poleTargetBone) {
  77613. this.poleTargetBone = options.poleTargetBone;
  77614. }
  77615. else if (this._bone1.getParent()) {
  77616. this.poleTargetBone = this._bone1.getParent();
  77617. }
  77618. if (options.poleTargetLocalOffset) {
  77619. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77620. }
  77621. if (options.poleAngle) {
  77622. this.poleAngle = options.poleAngle;
  77623. }
  77624. if (options.bendAxis) {
  77625. this._bendAxis.copyFrom(options.bendAxis);
  77626. }
  77627. if (options.maxAngle) {
  77628. this.maxAngle = options.maxAngle;
  77629. }
  77630. if (options.slerpAmount) {
  77631. this.slerpAmount = options.slerpAmount;
  77632. }
  77633. }
  77634. }
  77635. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77636. /**
  77637. * Gets or sets maximum allowed angle
  77638. */
  77639. get: function () {
  77640. return this._maxAngle;
  77641. },
  77642. set: function (value) {
  77643. this._setMaxAngle(value);
  77644. },
  77645. enumerable: true,
  77646. configurable: true
  77647. });
  77648. BoneIKController.prototype._setMaxAngle = function (ang) {
  77649. if (ang < 0) {
  77650. ang = 0;
  77651. }
  77652. if (ang > Math.PI || ang == undefined) {
  77653. ang = Math.PI;
  77654. }
  77655. this._maxAngle = ang;
  77656. var a = this._bone1Length;
  77657. var b = this._bone2Length;
  77658. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77659. };
  77660. /**
  77661. * Force the controller to update the bones
  77662. */
  77663. BoneIKController.prototype.update = function () {
  77664. var bone1 = this._bone1;
  77665. if (!bone1) {
  77666. return;
  77667. }
  77668. var target = this.targetPosition;
  77669. var poleTarget = this.poleTargetPosition;
  77670. var mat1 = BoneIKController._tmpMats[0];
  77671. var mat2 = BoneIKController._tmpMats[1];
  77672. if (this.targetMesh) {
  77673. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77674. }
  77675. if (this.poleTargetBone) {
  77676. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77677. }
  77678. else if (this.poleTargetMesh) {
  77679. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77680. }
  77681. var bonePos = BoneIKController._tmpVecs[0];
  77682. var zaxis = BoneIKController._tmpVecs[1];
  77683. var xaxis = BoneIKController._tmpVecs[2];
  77684. var yaxis = BoneIKController._tmpVecs[3];
  77685. var upAxis = BoneIKController._tmpVecs[4];
  77686. var _tmpQuat = BoneIKController._tmpQuat;
  77687. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77688. poleTarget.subtractToRef(bonePos, upAxis);
  77689. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77690. upAxis.y = 1;
  77691. }
  77692. else {
  77693. upAxis.normalize();
  77694. }
  77695. target.subtractToRef(bonePos, yaxis);
  77696. yaxis.normalize();
  77697. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77698. zaxis.normalize();
  77699. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77700. xaxis.normalize();
  77701. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77702. var a = this._bone1Length;
  77703. var b = this._bone2Length;
  77704. var c = BABYLON.Vector3.Distance(bonePos, target);
  77705. if (this._maxReach > 0) {
  77706. c = Math.min(this._maxReach, c);
  77707. }
  77708. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77709. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77710. if (acosa > 1) {
  77711. acosa = 1;
  77712. }
  77713. if (acosb > 1) {
  77714. acosb = 1;
  77715. }
  77716. if (acosa < -1) {
  77717. acosa = -1;
  77718. }
  77719. if (acosb < -1) {
  77720. acosb = -1;
  77721. }
  77722. var angA = Math.acos(acosa);
  77723. var angB = Math.acos(acosb);
  77724. var angC = -angA - angB;
  77725. if (this._rightHandedSystem) {
  77726. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77727. mat2.multiplyToRef(mat1, mat1);
  77728. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77729. mat2.multiplyToRef(mat1, mat1);
  77730. }
  77731. else {
  77732. var _tmpVec = BoneIKController._tmpVecs[5];
  77733. _tmpVec.copyFrom(this._bendAxis);
  77734. _tmpVec.x *= -1;
  77735. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77736. mat2.multiplyToRef(mat1, mat1);
  77737. }
  77738. if (this.poleAngle) {
  77739. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77740. mat1.multiplyToRef(mat2, mat1);
  77741. }
  77742. if (this._bone1) {
  77743. if (this.slerpAmount < 1) {
  77744. if (!this._slerping) {
  77745. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77746. }
  77747. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77748. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77749. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77750. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77751. this._slerping = true;
  77752. }
  77753. else {
  77754. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77755. this._bone1Mat.copyFrom(mat1);
  77756. this._slerping = false;
  77757. }
  77758. }
  77759. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77760. this._bone2Ang = angC;
  77761. };
  77762. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77763. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77764. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77765. return BoneIKController;
  77766. }());
  77767. BABYLON.BoneIKController = BoneIKController;
  77768. })(BABYLON || (BABYLON = {}));
  77769. //# sourceMappingURL=babylon.boneIKController.js.map
  77770. var BABYLON;
  77771. (function (BABYLON) {
  77772. /**
  77773. * Class used to make a bone look toward a point in space
  77774. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  77775. */
  77776. var BoneLookController = /** @class */ (function () {
  77777. /**
  77778. * Create a BoneLookController
  77779. * @param mesh the mesh that the bone belongs to
  77780. * @param bone the bone that will be looking to the target
  77781. * @param target the target Vector3 to look at
  77782. * @param settings optional settings:
  77783. * * maxYaw: the maximum angle the bone will yaw to
  77784. * * minYaw: the minimum angle the bone will yaw to
  77785. * * maxPitch: the maximum angle the bone will pitch to
  77786. * * minPitch: the minimum angle the bone will yaw to
  77787. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77788. * * upAxis: the up axis of the coordinate system
  77789. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77790. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  77791. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77792. * * adjustYaw: used to make an adjustment to the yaw of the bone
  77793. * * adjustPitch: used to make an adjustment to the pitch of the bone
  77794. * * adjustRoll: used to make an adjustment to the roll of the bone
  77795. **/
  77796. function BoneLookController(mesh, bone, target, options) {
  77797. /**
  77798. * The up axis of the coordinate system that is used when the bone is rotated
  77799. */
  77800. this.upAxis = BABYLON.Vector3.Up();
  77801. /**
  77802. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  77803. */
  77804. this.upAxisSpace = BABYLON.Space.LOCAL;
  77805. /**
  77806. * Used to make an adjustment to the yaw of the bone
  77807. */
  77808. this.adjustYaw = 0;
  77809. /**
  77810. * Used to make an adjustment to the pitch of the bone
  77811. */
  77812. this.adjustPitch = 0;
  77813. /**
  77814. * Used to make an adjustment to the roll of the bone
  77815. */
  77816. this.adjustRoll = 0;
  77817. /**
  77818. * 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)
  77819. */
  77820. this.slerpAmount = 1;
  77821. this._boneQuat = BABYLON.Quaternion.Identity();
  77822. this._slerping = false;
  77823. this._firstFrameSkipped = false;
  77824. this._fowardAxis = BABYLON.Vector3.Forward();
  77825. this.mesh = mesh;
  77826. this.bone = bone;
  77827. this.target = target;
  77828. if (options) {
  77829. if (options.adjustYaw) {
  77830. this.adjustYaw = options.adjustYaw;
  77831. }
  77832. if (options.adjustPitch) {
  77833. this.adjustPitch = options.adjustPitch;
  77834. }
  77835. if (options.adjustRoll) {
  77836. this.adjustRoll = options.adjustRoll;
  77837. }
  77838. if (options.maxYaw != null) {
  77839. this.maxYaw = options.maxYaw;
  77840. }
  77841. else {
  77842. this.maxYaw = Math.PI;
  77843. }
  77844. if (options.minYaw != null) {
  77845. this.minYaw = options.minYaw;
  77846. }
  77847. else {
  77848. this.minYaw = -Math.PI;
  77849. }
  77850. if (options.maxPitch != null) {
  77851. this.maxPitch = options.maxPitch;
  77852. }
  77853. else {
  77854. this.maxPitch = Math.PI;
  77855. }
  77856. if (options.minPitch != null) {
  77857. this.minPitch = options.minPitch;
  77858. }
  77859. else {
  77860. this.minPitch = -Math.PI;
  77861. }
  77862. if (options.slerpAmount != null) {
  77863. this.slerpAmount = options.slerpAmount;
  77864. }
  77865. if (options.upAxis != null) {
  77866. this.upAxis = options.upAxis;
  77867. }
  77868. if (options.upAxisSpace != null) {
  77869. this.upAxisSpace = options.upAxisSpace;
  77870. }
  77871. if (options.yawAxis != null || options.pitchAxis != null) {
  77872. var newYawAxis = BABYLON.Axis.Y;
  77873. var newPitchAxis = BABYLON.Axis.X;
  77874. if (options.yawAxis != null) {
  77875. newYawAxis = options.yawAxis.clone();
  77876. newYawAxis.normalize();
  77877. }
  77878. if (options.pitchAxis != null) {
  77879. newPitchAxis = options.pitchAxis.clone();
  77880. newPitchAxis.normalize();
  77881. }
  77882. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  77883. this._transformYawPitch = BABYLON.Matrix.Identity();
  77884. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  77885. this._transformYawPitchInv = this._transformYawPitch.clone();
  77886. this._transformYawPitch.invert();
  77887. }
  77888. }
  77889. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  77890. this.upAxisSpace = BABYLON.Space.LOCAL;
  77891. }
  77892. }
  77893. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  77894. /**
  77895. * Gets or sets the minimum yaw angle that the bone can look to
  77896. */
  77897. get: function () {
  77898. return this._minYaw;
  77899. },
  77900. set: function (value) {
  77901. this._minYaw = value;
  77902. this._minYawSin = Math.sin(value);
  77903. this._minYawCos = Math.cos(value);
  77904. if (this._maxYaw != null) {
  77905. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77906. this._yawRange = this._maxYaw - this._minYaw;
  77907. }
  77908. },
  77909. enumerable: true,
  77910. configurable: true
  77911. });
  77912. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  77913. /**
  77914. * Gets or sets the maximum yaw angle that the bone can look to
  77915. */
  77916. get: function () {
  77917. return this._maxYaw;
  77918. },
  77919. set: function (value) {
  77920. this._maxYaw = value;
  77921. this._maxYawSin = Math.sin(value);
  77922. this._maxYawCos = Math.cos(value);
  77923. if (this._minYaw != null) {
  77924. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  77925. this._yawRange = this._maxYaw - this._minYaw;
  77926. }
  77927. },
  77928. enumerable: true,
  77929. configurable: true
  77930. });
  77931. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  77932. /**
  77933. * Gets or sets the minimum pitch angle that the bone can look to
  77934. */
  77935. get: function () {
  77936. return this._minPitch;
  77937. },
  77938. set: function (value) {
  77939. this._minPitch = value;
  77940. this._minPitchTan = Math.tan(value);
  77941. },
  77942. enumerable: true,
  77943. configurable: true
  77944. });
  77945. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  77946. /**
  77947. * Gets or sets the maximum pitch angle that the bone can look to
  77948. */
  77949. get: function () {
  77950. return this._maxPitch;
  77951. },
  77952. set: function (value) {
  77953. this._maxPitch = value;
  77954. this._maxPitchTan = Math.tan(value);
  77955. },
  77956. enumerable: true,
  77957. configurable: true
  77958. });
  77959. /**
  77960. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  77961. */
  77962. BoneLookController.prototype.update = function () {
  77963. //skip the first frame when slerping so that the mesh rotation is correct
  77964. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  77965. this._firstFrameSkipped = true;
  77966. return;
  77967. }
  77968. var bone = this.bone;
  77969. var bonePos = BoneLookController._tmpVecs[0];
  77970. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  77971. var target = this.target;
  77972. var _tmpMat1 = BoneLookController._tmpMats[0];
  77973. var _tmpMat2 = BoneLookController._tmpMats[1];
  77974. var mesh = this.mesh;
  77975. var parentBone = bone.getParent();
  77976. var upAxis = BoneLookController._tmpVecs[1];
  77977. upAxis.copyFrom(this.upAxis);
  77978. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  77979. if (this._transformYawPitch) {
  77980. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  77981. }
  77982. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  77983. }
  77984. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  77985. mesh.getDirectionToRef(upAxis, upAxis);
  77986. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  77987. upAxis.normalize();
  77988. }
  77989. }
  77990. var checkYaw = false;
  77991. var checkPitch = false;
  77992. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  77993. checkYaw = true;
  77994. }
  77995. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  77996. checkPitch = true;
  77997. }
  77998. if (checkYaw || checkPitch) {
  77999. var spaceMat = BoneLookController._tmpMats[2];
  78000. var spaceMatInv = BoneLookController._tmpMats[3];
  78001. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78002. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78003. }
  78004. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78005. spaceMat.copyFrom(mesh.getWorldMatrix());
  78006. }
  78007. else {
  78008. var forwardAxis = BoneLookController._tmpVecs[2];
  78009. forwardAxis.copyFrom(this._fowardAxis);
  78010. if (this._transformYawPitch) {
  78011. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78012. }
  78013. if (parentBone) {
  78014. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78015. }
  78016. else {
  78017. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78018. }
  78019. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78020. rightAxis.normalize();
  78021. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78022. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78023. }
  78024. spaceMat.invertToRef(spaceMatInv);
  78025. var xzlen = null;
  78026. if (checkPitch) {
  78027. var localTarget = BoneLookController._tmpVecs[3];
  78028. target.subtractToRef(bonePos, localTarget);
  78029. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78030. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78031. var pitch = Math.atan2(localTarget.y, xzlen);
  78032. var newPitch = pitch;
  78033. if (pitch > this._maxPitch) {
  78034. localTarget.y = this._maxPitchTan * xzlen;
  78035. newPitch = this._maxPitch;
  78036. }
  78037. else if (pitch < this._minPitch) {
  78038. localTarget.y = this._minPitchTan * xzlen;
  78039. newPitch = this._minPitch;
  78040. }
  78041. if (pitch != newPitch) {
  78042. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78043. localTarget.addInPlace(bonePos);
  78044. target = localTarget;
  78045. }
  78046. }
  78047. if (checkYaw) {
  78048. var localTarget = BoneLookController._tmpVecs[4];
  78049. target.subtractToRef(bonePos, localTarget);
  78050. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78051. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78052. var newYaw = yaw;
  78053. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78054. if (xzlen == null) {
  78055. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78056. }
  78057. if (this._yawRange > Math.PI) {
  78058. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78059. localTarget.z = this._maxYawCos * xzlen;
  78060. localTarget.x = this._maxYawSin * xzlen;
  78061. newYaw = this._maxYaw;
  78062. }
  78063. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78064. localTarget.z = this._minYawCos * xzlen;
  78065. localTarget.x = this._minYawSin * xzlen;
  78066. newYaw = this._minYaw;
  78067. }
  78068. }
  78069. else {
  78070. if (yaw > this._maxYaw) {
  78071. localTarget.z = this._maxYawCos * xzlen;
  78072. localTarget.x = this._maxYawSin * xzlen;
  78073. newYaw = this._maxYaw;
  78074. }
  78075. else if (yaw < this._minYaw) {
  78076. localTarget.z = this._minYawCos * xzlen;
  78077. localTarget.x = this._minYawSin * xzlen;
  78078. newYaw = this._minYaw;
  78079. }
  78080. }
  78081. }
  78082. if (this._slerping && this._yawRange > Math.PI) {
  78083. //are we going to be crossing into the min/max region?
  78084. var boneFwd = BoneLookController._tmpVecs[8];
  78085. boneFwd.copyFrom(BABYLON.Axis.Z);
  78086. if (this._transformYawPitch) {
  78087. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78088. }
  78089. var boneRotMat = BoneLookController._tmpMats[4];
  78090. this._boneQuat.toRotationMatrix(boneRotMat);
  78091. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78092. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78093. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78094. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78095. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78096. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78097. if (angBtwTar > angBtwMidYaw) {
  78098. if (xzlen == null) {
  78099. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78100. }
  78101. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78102. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78103. if (angBtwMin < angBtwMax) {
  78104. newYaw = boneYaw + Math.PI * .75;
  78105. localTarget.z = Math.cos(newYaw) * xzlen;
  78106. localTarget.x = Math.sin(newYaw) * xzlen;
  78107. }
  78108. else {
  78109. newYaw = boneYaw - Math.PI * .75;
  78110. localTarget.z = Math.cos(newYaw) * xzlen;
  78111. localTarget.x = Math.sin(newYaw) * xzlen;
  78112. }
  78113. }
  78114. }
  78115. if (yaw != newYaw) {
  78116. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78117. localTarget.addInPlace(bonePos);
  78118. target = localTarget;
  78119. }
  78120. }
  78121. }
  78122. var zaxis = BoneLookController._tmpVecs[5];
  78123. var xaxis = BoneLookController._tmpVecs[6];
  78124. var yaxis = BoneLookController._tmpVecs[7];
  78125. var _tmpQuat = BoneLookController._tmpQuat;
  78126. target.subtractToRef(bonePos, zaxis);
  78127. zaxis.normalize();
  78128. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78129. xaxis.normalize();
  78130. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78131. yaxis.normalize();
  78132. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78133. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78134. return;
  78135. }
  78136. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78137. return;
  78138. }
  78139. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78140. return;
  78141. }
  78142. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78143. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78144. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78145. }
  78146. if (this.slerpAmount < 1) {
  78147. if (!this._slerping) {
  78148. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78149. }
  78150. if (this._transformYawPitch) {
  78151. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78152. }
  78153. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78154. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78155. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78156. this._slerping = true;
  78157. }
  78158. else {
  78159. if (this._transformYawPitch) {
  78160. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78161. }
  78162. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78163. this._slerping = false;
  78164. }
  78165. };
  78166. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78167. var angDiff = ang2 - ang1;
  78168. angDiff %= Math.PI * 2;
  78169. if (angDiff > Math.PI) {
  78170. angDiff -= Math.PI * 2;
  78171. }
  78172. else if (angDiff < -Math.PI) {
  78173. angDiff += Math.PI * 2;
  78174. }
  78175. return angDiff;
  78176. };
  78177. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78178. ang1 %= (2 * Math.PI);
  78179. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78180. ang2 %= (2 * Math.PI);
  78181. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78182. var ab = 0;
  78183. if (ang1 < ang2) {
  78184. ab = ang2 - ang1;
  78185. }
  78186. else {
  78187. ab = ang1 - ang2;
  78188. }
  78189. if (ab > Math.PI) {
  78190. ab = Math.PI * 2 - ab;
  78191. }
  78192. return ab;
  78193. };
  78194. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78195. ang %= (2 * Math.PI);
  78196. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78197. ang1 %= (2 * Math.PI);
  78198. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78199. ang2 %= (2 * Math.PI);
  78200. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78201. if (ang1 < ang2) {
  78202. if (ang > ang1 && ang < ang2) {
  78203. return true;
  78204. }
  78205. }
  78206. else {
  78207. if (ang > ang2 && ang < ang1) {
  78208. return true;
  78209. }
  78210. }
  78211. return false;
  78212. };
  78213. 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()];
  78214. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78215. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78216. return BoneLookController;
  78217. }());
  78218. BABYLON.BoneLookController = BoneLookController;
  78219. })(BABYLON || (BABYLON = {}));
  78220. //# sourceMappingURL=babylon.boneLookController.js.map
  78221. var BABYLON;
  78222. (function (BABYLON) {
  78223. /**
  78224. * Class used to handle skinning animations
  78225. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78226. */
  78227. var Skeleton = /** @class */ (function () {
  78228. /**
  78229. * Creates a new skeleton
  78230. * @param name defines the skeleton name
  78231. * @param id defines the skeleton Id
  78232. * @param scene defines the hosting scene
  78233. */
  78234. function Skeleton(
  78235. /** defines the skeleton name */
  78236. name,
  78237. /** defines the skeleton Id */
  78238. id, scene) {
  78239. this.name = name;
  78240. this.id = id;
  78241. /**
  78242. * Gets the list of child bones
  78243. */
  78244. this.bones = new Array();
  78245. /**
  78246. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78247. */
  78248. this.needInitialSkinMatrix = false;
  78249. this._isDirty = true;
  78250. this._meshesWithPoseMatrix = new Array();
  78251. this._identity = BABYLON.Matrix.Identity();
  78252. this._ranges = {};
  78253. this._lastAbsoluteTransformsUpdateId = -1;
  78254. /**
  78255. * Specifies if the skeleton should be serialized
  78256. */
  78257. this.doNotSerialize = false;
  78258. this._animationPropertiesOverride = null;
  78259. // Events
  78260. /**
  78261. * An observable triggered before computing the skeleton's matrices
  78262. */
  78263. this.onBeforeComputeObservable = new BABYLON.Observable();
  78264. this.bones = [];
  78265. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78266. scene.skeletons.push(this);
  78267. //make sure it will recalculate the matrix next time prepare is called.
  78268. this._isDirty = true;
  78269. }
  78270. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78271. /**
  78272. * Gets or sets the animation properties override
  78273. */
  78274. get: function () {
  78275. if (!this._animationPropertiesOverride) {
  78276. return this._scene.animationPropertiesOverride;
  78277. }
  78278. return this._animationPropertiesOverride;
  78279. },
  78280. set: function (value) {
  78281. this._animationPropertiesOverride = value;
  78282. },
  78283. enumerable: true,
  78284. configurable: true
  78285. });
  78286. // Members
  78287. /**
  78288. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78289. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78290. * @returns a Float32Array containing matrices data
  78291. */
  78292. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78293. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78294. return mesh._bonesTransformMatrices;
  78295. }
  78296. if (!this._transformMatrices) {
  78297. this.prepare();
  78298. }
  78299. return this._transformMatrices;
  78300. };
  78301. /**
  78302. * Gets the current hosting scene
  78303. * @returns a scene object
  78304. */
  78305. Skeleton.prototype.getScene = function () {
  78306. return this._scene;
  78307. };
  78308. // Methods
  78309. /**
  78310. * Gets a string representing the current skeleton data
  78311. * @param fullDetails defines a boolean indicating if we want a verbose version
  78312. * @returns a string representing the current skeleton data
  78313. */
  78314. Skeleton.prototype.toString = function (fullDetails) {
  78315. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78316. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78317. if (fullDetails) {
  78318. ret += ", Ranges: {";
  78319. var first = true;
  78320. for (var name_1 in this._ranges) {
  78321. if (first) {
  78322. ret += ", ";
  78323. first = false;
  78324. }
  78325. ret += name_1;
  78326. }
  78327. ret += "}";
  78328. }
  78329. return ret;
  78330. };
  78331. /**
  78332. * Get bone's index searching by name
  78333. * @param name defines bone's name to search for
  78334. * @return the indice of the bone. Returns -1 if not found
  78335. */
  78336. Skeleton.prototype.getBoneIndexByName = function (name) {
  78337. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78338. if (this.bones[boneIndex].name === name) {
  78339. return boneIndex;
  78340. }
  78341. }
  78342. return -1;
  78343. };
  78344. /**
  78345. * Creater a new animation range
  78346. * @param name defines the name of the range
  78347. * @param from defines the start key
  78348. * @param to defines the end key
  78349. */
  78350. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78351. // check name not already in use
  78352. if (!this._ranges[name]) {
  78353. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78354. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78355. if (this.bones[i].animations[0]) {
  78356. this.bones[i].animations[0].createRange(name, from, to);
  78357. }
  78358. }
  78359. }
  78360. };
  78361. /**
  78362. * Delete a specific animation range
  78363. * @param name defines the name of the range
  78364. * @param deleteFrames defines if frames must be removed as well
  78365. */
  78366. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78367. if (deleteFrames === void 0) { deleteFrames = true; }
  78368. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78369. if (this.bones[i].animations[0]) {
  78370. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78371. }
  78372. }
  78373. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78374. };
  78375. /**
  78376. * Gets a specific animation range
  78377. * @param name defines the name of the range to look for
  78378. * @returns the requested animation range or null if not found
  78379. */
  78380. Skeleton.prototype.getAnimationRange = function (name) {
  78381. return this._ranges[name];
  78382. };
  78383. /**
  78384. * Gets the list of all animation ranges defined on this skeleton
  78385. * @returns an array
  78386. */
  78387. Skeleton.prototype.getAnimationRanges = function () {
  78388. var animationRanges = [];
  78389. var name;
  78390. var i = 0;
  78391. for (name in this._ranges) {
  78392. animationRanges[i] = this._ranges[name];
  78393. i++;
  78394. }
  78395. return animationRanges;
  78396. };
  78397. /**
  78398. * Copy animation range from a source skeleton.
  78399. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  78400. * @param source defines the source skeleton
  78401. * @param name defines the name of the range to copy
  78402. * @param rescaleAsRequired defines if rescaling must be applied if required
  78403. * @returns true if operation was successful
  78404. */
  78405. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  78406. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78407. if (this._ranges[name] || !source.getAnimationRange(name)) {
  78408. return false;
  78409. }
  78410. var ret = true;
  78411. var frameOffset = this._getHighestAnimationFrame() + 1;
  78412. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  78413. var boneDict = {};
  78414. var sourceBones = source.bones;
  78415. var nBones;
  78416. var i;
  78417. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  78418. boneDict[sourceBones[i].name] = sourceBones[i];
  78419. }
  78420. if (this.bones.length !== sourceBones.length) {
  78421. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  78422. ret = false;
  78423. }
  78424. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  78425. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  78426. var boneName = this.bones[i].name;
  78427. var sourceBone = boneDict[boneName];
  78428. if (sourceBone) {
  78429. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  78430. }
  78431. else {
  78432. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  78433. ret = false;
  78434. }
  78435. }
  78436. // do not call createAnimationRange(), since it also is done to bones, which was already done
  78437. var range = source.getAnimationRange(name);
  78438. if (range) {
  78439. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  78440. }
  78441. return ret;
  78442. };
  78443. /**
  78444. * Forces the skeleton to go to rest pose
  78445. */
  78446. Skeleton.prototype.returnToRest = function () {
  78447. for (var index = 0; index < this.bones.length; index++) {
  78448. this.bones[index].returnToRest();
  78449. }
  78450. };
  78451. Skeleton.prototype._getHighestAnimationFrame = function () {
  78452. var ret = 0;
  78453. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78454. if (this.bones[i].animations[0]) {
  78455. var highest = this.bones[i].animations[0].getHighestFrame();
  78456. if (ret < highest) {
  78457. ret = highest;
  78458. }
  78459. }
  78460. }
  78461. return ret;
  78462. };
  78463. /**
  78464. * Begin a specific animation range
  78465. * @param name defines the name of the range to start
  78466. * @param loop defines if looping must be turned on (false by default)
  78467. * @param speedRatio defines the speed ratio to apply (1 by default)
  78468. * @param onAnimationEnd defines a callback which will be called when animation will end
  78469. * @returns a new animatable
  78470. */
  78471. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  78472. var range = this.getAnimationRange(name);
  78473. if (!range) {
  78474. return null;
  78475. }
  78476. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  78477. };
  78478. /** @ignore */
  78479. Skeleton.prototype._markAsDirty = function () {
  78480. this._isDirty = true;
  78481. };
  78482. /** @ignore */
  78483. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  78484. this._meshesWithPoseMatrix.push(mesh);
  78485. };
  78486. /** @ignore */
  78487. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  78488. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  78489. if (index > -1) {
  78490. this._meshesWithPoseMatrix.splice(index, 1);
  78491. }
  78492. };
  78493. /** @ignore */
  78494. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  78495. this.onBeforeComputeObservable.notifyObservers(this);
  78496. for (var index = 0; index < this.bones.length; index++) {
  78497. var bone = this.bones[index];
  78498. var parentBone = bone.getParent();
  78499. if (parentBone) {
  78500. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  78501. }
  78502. else {
  78503. if (initialSkinMatrix) {
  78504. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  78505. }
  78506. else {
  78507. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  78508. }
  78509. }
  78510. if (bone._index !== -1) {
  78511. var mappedIndex = bone._index === null ? index : bone._index;
  78512. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  78513. }
  78514. }
  78515. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  78516. };
  78517. /**
  78518. * Build all resources required to render a skeleton
  78519. */
  78520. Skeleton.prototype.prepare = function () {
  78521. if (!this._isDirty) {
  78522. return;
  78523. }
  78524. if (this.needInitialSkinMatrix) {
  78525. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  78526. var mesh = this._meshesWithPoseMatrix[index];
  78527. var poseMatrix = mesh.getPoseMatrix();
  78528. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  78529. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78530. }
  78531. if (this._synchronizedWithMesh !== mesh) {
  78532. this._synchronizedWithMesh = mesh;
  78533. // Prepare bones
  78534. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  78535. var bone = this.bones[boneIndex];
  78536. if (!bone.getParent()) {
  78537. var matrix = bone.getBaseMatrix();
  78538. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  78539. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  78540. }
  78541. }
  78542. }
  78543. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  78544. }
  78545. }
  78546. else {
  78547. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  78548. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78549. }
  78550. this._computeTransformMatrices(this._transformMatrices, null);
  78551. }
  78552. this._isDirty = false;
  78553. this._scene._activeBones.addCount(this.bones.length, false);
  78554. };
  78555. /**
  78556. * Gets the list of animatables currently running for this skeleton
  78557. * @returns an array of animatables
  78558. */
  78559. Skeleton.prototype.getAnimatables = function () {
  78560. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78561. this._animatables = [];
  78562. for (var index = 0; index < this.bones.length; index++) {
  78563. this._animatables.push(this.bones[index]);
  78564. }
  78565. }
  78566. return this._animatables;
  78567. };
  78568. /**
  78569. * Clone the current skeleton
  78570. * @param name defines the name of the new skeleton
  78571. * @param id defines the id of the enw skeleton
  78572. * @returns the new skeleton
  78573. */
  78574. Skeleton.prototype.clone = function (name, id) {
  78575. var result = new Skeleton(name, id || name, this._scene);
  78576. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78577. for (var index = 0; index < this.bones.length; index++) {
  78578. var source = this.bones[index];
  78579. var parentBone = null;
  78580. var parent_1 = source.getParent();
  78581. if (parent_1) {
  78582. var parentIndex = this.bones.indexOf(parent_1);
  78583. parentBone = result.bones[parentIndex];
  78584. }
  78585. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78586. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78587. }
  78588. if (this._ranges) {
  78589. result._ranges = {};
  78590. for (var rangeName in this._ranges) {
  78591. var range = this._ranges[rangeName];
  78592. if (range) {
  78593. result._ranges[rangeName] = range.clone();
  78594. }
  78595. }
  78596. }
  78597. this._isDirty = true;
  78598. return result;
  78599. };
  78600. /**
  78601. * Enable animation blending for this skeleton
  78602. * @param blendingSpeed defines the blending speed to apply
  78603. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  78604. */
  78605. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78606. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78607. this.bones.forEach(function (bone) {
  78608. bone.animations.forEach(function (animation) {
  78609. animation.enableBlending = true;
  78610. animation.blendingSpeed = blendingSpeed;
  78611. });
  78612. });
  78613. };
  78614. /**
  78615. * Releases all resources associated with the current skeleton
  78616. */
  78617. Skeleton.prototype.dispose = function () {
  78618. this._meshesWithPoseMatrix = [];
  78619. // Animations
  78620. this.getScene().stopAnimation(this);
  78621. // Remove from scene
  78622. this.getScene().removeSkeleton(this);
  78623. };
  78624. /**
  78625. * Serialize the skeleton in a JSON object
  78626. * @returns a JSON object
  78627. */
  78628. Skeleton.prototype.serialize = function () {
  78629. var serializationObject = {};
  78630. serializationObject.name = this.name;
  78631. serializationObject.id = this.id;
  78632. if (this.dimensionsAtRest) {
  78633. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78634. }
  78635. serializationObject.bones = [];
  78636. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78637. for (var index = 0; index < this.bones.length; index++) {
  78638. var bone = this.bones[index];
  78639. var parent_2 = bone.getParent();
  78640. var serializedBone = {
  78641. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78642. name: bone.name,
  78643. matrix: bone.getBaseMatrix().toArray(),
  78644. rest: bone.getRestPose().toArray()
  78645. };
  78646. serializationObject.bones.push(serializedBone);
  78647. if (bone.length) {
  78648. serializedBone.length = bone.length;
  78649. }
  78650. if (bone.animations && bone.animations.length > 0) {
  78651. serializedBone.animation = bone.animations[0].serialize();
  78652. }
  78653. serializationObject.ranges = [];
  78654. for (var name in this._ranges) {
  78655. var source = this._ranges[name];
  78656. if (!source) {
  78657. continue;
  78658. }
  78659. var range = {};
  78660. range.name = name;
  78661. range.from = source.from;
  78662. range.to = source.to;
  78663. serializationObject.ranges.push(range);
  78664. }
  78665. }
  78666. return serializationObject;
  78667. };
  78668. /**
  78669. * Creates a new skeleton from serialized data
  78670. * @param parsedSkeleton defines the serialized data
  78671. * @param scene defines the hosting scene
  78672. * @returns a new skeleton
  78673. */
  78674. Skeleton.Parse = function (parsedSkeleton, scene) {
  78675. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78676. if (parsedSkeleton.dimensionsAtRest) {
  78677. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78678. }
  78679. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78680. var index;
  78681. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78682. var parsedBone = parsedSkeleton.bones[index];
  78683. var parentBone = null;
  78684. if (parsedBone.parentBoneIndex > -1) {
  78685. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78686. }
  78687. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78688. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78689. if (parsedBone.length) {
  78690. bone.length = parsedBone.length;
  78691. }
  78692. if (parsedBone.animation) {
  78693. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78694. }
  78695. }
  78696. // placed after bones, so createAnimationRange can cascade down
  78697. if (parsedSkeleton.ranges) {
  78698. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78699. var data = parsedSkeleton.ranges[index];
  78700. skeleton.createAnimationRange(data.name, data.from, data.to);
  78701. }
  78702. }
  78703. return skeleton;
  78704. };
  78705. /**
  78706. * Compute all node absolute transforms
  78707. * @param forceUpdate defines if computation must be done even if cache is up to date
  78708. */
  78709. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78710. if (forceUpdate === void 0) { forceUpdate = false; }
  78711. var renderId = this._scene.getRenderId();
  78712. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78713. this.bones[0].computeAbsoluteTransforms();
  78714. this._lastAbsoluteTransformsUpdateId = renderId;
  78715. }
  78716. };
  78717. /**
  78718. * Gets the root pose matrix
  78719. * @returns a matrix
  78720. */
  78721. Skeleton.prototype.getPoseMatrix = function () {
  78722. var poseMatrix = null;
  78723. if (this._meshesWithPoseMatrix.length > 0) {
  78724. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78725. }
  78726. return poseMatrix;
  78727. };
  78728. /**
  78729. * Sorts bones per internal index
  78730. */
  78731. Skeleton.prototype.sortBones = function () {
  78732. var bones = new Array();
  78733. var visited = new Array(this.bones.length);
  78734. for (var index = 0; index < this.bones.length; index++) {
  78735. this._sortBones(index, bones, visited);
  78736. }
  78737. this.bones = bones;
  78738. };
  78739. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78740. if (visited[index]) {
  78741. return;
  78742. }
  78743. visited[index] = true;
  78744. var bone = this.bones[index];
  78745. if (bone._index === undefined) {
  78746. bone._index = index;
  78747. }
  78748. var parentBone = bone.getParent();
  78749. if (parentBone) {
  78750. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78751. }
  78752. bones.push(bone);
  78753. };
  78754. return Skeleton;
  78755. }());
  78756. BABYLON.Skeleton = Skeleton;
  78757. })(BABYLON || (BABYLON = {}));
  78758. //# sourceMappingURL=babylon.skeleton.js.map
  78759. var BABYLON;
  78760. (function (BABYLON) {
  78761. var SphericalPolynomial = /** @class */ (function () {
  78762. function SphericalPolynomial() {
  78763. this.x = BABYLON.Vector3.Zero();
  78764. this.y = BABYLON.Vector3.Zero();
  78765. this.z = BABYLON.Vector3.Zero();
  78766. this.xx = BABYLON.Vector3.Zero();
  78767. this.yy = BABYLON.Vector3.Zero();
  78768. this.zz = BABYLON.Vector3.Zero();
  78769. this.xy = BABYLON.Vector3.Zero();
  78770. this.yz = BABYLON.Vector3.Zero();
  78771. this.zx = BABYLON.Vector3.Zero();
  78772. }
  78773. SphericalPolynomial.prototype.addAmbient = function (color) {
  78774. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78775. this.xx = this.xx.add(colorVector);
  78776. this.yy = this.yy.add(colorVector);
  78777. this.zz = this.zz.add(colorVector);
  78778. };
  78779. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78780. var result = new SphericalPolynomial();
  78781. result.x = harmonics.L11.scale(1.02333);
  78782. result.y = harmonics.L1_1.scale(1.02333);
  78783. result.z = harmonics.L10.scale(1.02333);
  78784. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78785. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78786. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78787. result.yz = harmonics.L2_1.scale(0.858086);
  78788. result.zx = harmonics.L21.scale(0.858086);
  78789. result.xy = harmonics.L2_2.scale(0.858086);
  78790. result.scale(1.0 / Math.PI);
  78791. return result;
  78792. };
  78793. SphericalPolynomial.prototype.scale = function (scale) {
  78794. this.x = this.x.scale(scale);
  78795. this.y = this.y.scale(scale);
  78796. this.z = this.z.scale(scale);
  78797. this.xx = this.xx.scale(scale);
  78798. this.yy = this.yy.scale(scale);
  78799. this.zz = this.zz.scale(scale);
  78800. this.yz = this.yz.scale(scale);
  78801. this.zx = this.zx.scale(scale);
  78802. this.xy = this.xy.scale(scale);
  78803. };
  78804. return SphericalPolynomial;
  78805. }());
  78806. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78807. var SphericalHarmonics = /** @class */ (function () {
  78808. function SphericalHarmonics() {
  78809. this.L00 = BABYLON.Vector3.Zero();
  78810. this.L1_1 = BABYLON.Vector3.Zero();
  78811. this.L10 = BABYLON.Vector3.Zero();
  78812. this.L11 = BABYLON.Vector3.Zero();
  78813. this.L2_2 = BABYLON.Vector3.Zero();
  78814. this.L2_1 = BABYLON.Vector3.Zero();
  78815. this.L20 = BABYLON.Vector3.Zero();
  78816. this.L21 = BABYLON.Vector3.Zero();
  78817. this.L22 = BABYLON.Vector3.Zero();
  78818. }
  78819. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78820. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78821. var c = colorVector.scale(deltaSolidAngle);
  78822. this.L00 = this.L00.add(c.scale(0.282095));
  78823. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78824. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78825. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78826. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78827. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78828. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78829. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78830. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78831. };
  78832. SphericalHarmonics.prototype.scale = function (scale) {
  78833. this.L00 = this.L00.scale(scale);
  78834. this.L1_1 = this.L1_1.scale(scale);
  78835. this.L10 = this.L10.scale(scale);
  78836. this.L11 = this.L11.scale(scale);
  78837. this.L2_2 = this.L2_2.scale(scale);
  78838. this.L2_1 = this.L2_1.scale(scale);
  78839. this.L20 = this.L20.scale(scale);
  78840. this.L21 = this.L21.scale(scale);
  78841. this.L22 = this.L22.scale(scale);
  78842. };
  78843. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  78844. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  78845. //
  78846. // E_lm = A_l * L_lm
  78847. //
  78848. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  78849. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  78850. // the scaling factors are given in equation 9.
  78851. // Constant (Band 0)
  78852. this.L00 = this.L00.scale(3.141593);
  78853. // Linear (Band 1)
  78854. this.L1_1 = this.L1_1.scale(2.094395);
  78855. this.L10 = this.L10.scale(2.094395);
  78856. this.L11 = this.L11.scale(2.094395);
  78857. // Quadratic (Band 2)
  78858. this.L2_2 = this.L2_2.scale(0.785398);
  78859. this.L2_1 = this.L2_1.scale(0.785398);
  78860. this.L20 = this.L20.scale(0.785398);
  78861. this.L21 = this.L21.scale(0.785398);
  78862. this.L22 = this.L22.scale(0.785398);
  78863. };
  78864. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  78865. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  78866. // L = (1/pi) * E * rho
  78867. //
  78868. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  78869. this.scale(1.0 / Math.PI);
  78870. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  78871. // (The pixel shader must apply albedo after texture fetches, etc).
  78872. };
  78873. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  78874. var result = new SphericalHarmonics();
  78875. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  78876. result.L1_1 = polynomial.y.scale(0.977204);
  78877. result.L10 = polynomial.z.scale(0.977204);
  78878. result.L11 = polynomial.x.scale(0.977204);
  78879. result.L2_2 = polynomial.xy.scale(1.16538);
  78880. result.L2_1 = polynomial.yz.scale(1.16538);
  78881. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  78882. result.L21 = polynomial.zx.scale(1.16538);
  78883. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  78884. result.scale(Math.PI);
  78885. return result;
  78886. };
  78887. return SphericalHarmonics;
  78888. }());
  78889. BABYLON.SphericalHarmonics = SphericalHarmonics;
  78890. })(BABYLON || (BABYLON = {}));
  78891. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  78892. var BABYLON;
  78893. (function (BABYLON) {
  78894. var FileFaceOrientation = /** @class */ (function () {
  78895. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  78896. this.name = name;
  78897. this.worldAxisForNormal = worldAxisForNormal;
  78898. this.worldAxisForFileX = worldAxisForFileX;
  78899. this.worldAxisForFileY = worldAxisForFileY;
  78900. }
  78901. return FileFaceOrientation;
  78902. }());
  78903. ;
  78904. /**
  78905. * Helper class dealing with the extraction of spherical polynomial dataArray
  78906. * from a cube map.
  78907. */
  78908. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  78909. function CubeMapToSphericalPolynomialTools() {
  78910. }
  78911. /**
  78912. * Converts a texture to the according Spherical Polynomial data.
  78913. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78914. *
  78915. * @param texture The texture to extract the information from.
  78916. * @return The Spherical Polynomial data.
  78917. */
  78918. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  78919. if (!texture.isCube) {
  78920. // Only supports cube Textures currently.
  78921. return null;
  78922. }
  78923. var size = texture.getSize().width;
  78924. var right = texture.readPixels(0);
  78925. var left = texture.readPixels(1);
  78926. var up;
  78927. var down;
  78928. if (texture.isRenderTarget) {
  78929. up = texture.readPixels(3);
  78930. down = texture.readPixels(2);
  78931. }
  78932. else {
  78933. up = texture.readPixels(2);
  78934. down = texture.readPixels(3);
  78935. }
  78936. var front = texture.readPixels(4);
  78937. var back = texture.readPixels(5);
  78938. var gammaSpace = texture.gammaSpace;
  78939. // Always read as RGBA.
  78940. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  78941. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78942. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78943. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  78944. }
  78945. var cubeInfo = {
  78946. size: size,
  78947. right: right,
  78948. left: left,
  78949. up: up,
  78950. down: down,
  78951. front: front,
  78952. back: back,
  78953. format: format,
  78954. type: type,
  78955. gammaSpace: gammaSpace,
  78956. };
  78957. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  78958. };
  78959. /**
  78960. * Converts a cubemap to the according Spherical Polynomial data.
  78961. * This extracts the first 3 orders only as they are the only one used in the lighting.
  78962. *
  78963. * @param cubeInfo The Cube map to extract the information from.
  78964. * @return The Spherical Polynomial data.
  78965. */
  78966. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  78967. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  78968. var totalSolidAngle = 0.0;
  78969. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  78970. var du = 2.0 / cubeInfo.size;
  78971. var dv = du;
  78972. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  78973. var minUV = du * 0.5 - 1.0;
  78974. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  78975. var fileFace = this.FileFaces[faceIndex];
  78976. var dataArray = cubeInfo[fileFace.name];
  78977. var v = minUV;
  78978. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  78979. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  78980. // Because SP is still linear, so summation is fine in that basis.
  78981. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  78982. for (var y = 0; y < cubeInfo.size; y++) {
  78983. var u = minUV;
  78984. for (var x = 0; x < cubeInfo.size; x++) {
  78985. // World direction (not normalised)
  78986. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  78987. worldDirection.normalize();
  78988. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  78989. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  78990. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  78991. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  78992. // Handle Integer types.
  78993. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  78994. r /= 255;
  78995. g /= 255;
  78996. b /= 255;
  78997. }
  78998. // Handle Gamma space textures.
  78999. if (cubeInfo.gammaSpace) {
  79000. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79001. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79002. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79003. }
  79004. var color = new BABYLON.Color3(r, g, b);
  79005. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79006. totalSolidAngle += deltaSolidAngle;
  79007. u += du;
  79008. }
  79009. v += dv;
  79010. }
  79011. }
  79012. // Solid angle for entire sphere is 4*pi
  79013. var sphereSolidAngle = 4.0 * Math.PI;
  79014. // Adjust the solid angle to allow for how many faces we processed.
  79015. var facesProcessed = 6.0;
  79016. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79017. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79018. // This is needed because the numerical integration over the cube uses a
  79019. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79020. // and also to compensate for accumulative error due to float precision in the summation.
  79021. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79022. sphericalHarmonics.scale(correctionFactor);
  79023. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79024. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79025. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79026. };
  79027. CubeMapToSphericalPolynomialTools.FileFaces = [
  79028. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79029. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79030. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79031. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79032. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79033. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79034. ];
  79035. return CubeMapToSphericalPolynomialTools;
  79036. }());
  79037. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79038. })(BABYLON || (BABYLON = {}));
  79039. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79040. var BABYLON;
  79041. (function (BABYLON) {
  79042. /**
  79043. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79044. */
  79045. var PanoramaToCubeMapTools = /** @class */ (function () {
  79046. function PanoramaToCubeMapTools() {
  79047. }
  79048. /**
  79049. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79050. *
  79051. * @param float32Array The source data.
  79052. * @param inputWidth The width of the input panorama.
  79053. * @param inputhHeight The height of the input panorama.
  79054. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79055. * @return The cubemap data
  79056. */
  79057. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79058. if (!float32Array) {
  79059. throw "ConvertPanoramaToCubemap: input cannot be null";
  79060. }
  79061. if (float32Array.length != inputWidth * inputHeight * 3) {
  79062. throw "ConvertPanoramaToCubemap: input size is wrong";
  79063. }
  79064. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79065. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79066. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79067. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79068. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79069. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79070. return {
  79071. front: textureFront,
  79072. back: textureBack,
  79073. left: textureLeft,
  79074. right: textureRight,
  79075. up: textureUp,
  79076. down: textureDown,
  79077. size: size,
  79078. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79079. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79080. gammaSpace: false,
  79081. };
  79082. };
  79083. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79084. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79085. var textureArray = new Float32Array(buffer);
  79086. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79087. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79088. var dy = 1 / texSize;
  79089. var fy = 0;
  79090. for (var y = 0; y < texSize; y++) {
  79091. var xv1 = faceData[0];
  79092. var xv2 = faceData[2];
  79093. for (var x = 0; x < texSize; x++) {
  79094. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79095. v.normalize();
  79096. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79097. // 3 channels per pixels
  79098. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79099. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79100. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79101. xv1 = xv1.add(rotDX1);
  79102. xv2 = xv2.add(rotDX2);
  79103. }
  79104. fy += dy;
  79105. }
  79106. return textureArray;
  79107. };
  79108. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79109. var theta = Math.atan2(vDir.z, vDir.x);
  79110. var phi = Math.acos(vDir.y);
  79111. while (theta < -Math.PI)
  79112. theta += 2 * Math.PI;
  79113. while (theta > Math.PI)
  79114. theta -= 2 * Math.PI;
  79115. var dx = theta / Math.PI;
  79116. var dy = phi / Math.PI;
  79117. // recenter.
  79118. dx = dx * 0.5 + 0.5;
  79119. var px = Math.round(dx * inputWidth);
  79120. if (px < 0)
  79121. px = 0;
  79122. else if (px >= inputWidth)
  79123. px = inputWidth - 1;
  79124. var py = Math.round(dy * inputHeight);
  79125. if (py < 0)
  79126. py = 0;
  79127. else if (py >= inputHeight)
  79128. py = inputHeight - 1;
  79129. var inputY = (inputHeight - py - 1);
  79130. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79131. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79132. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79133. return {
  79134. r: r,
  79135. g: g,
  79136. b: b
  79137. };
  79138. };
  79139. PanoramaToCubeMapTools.FACE_FRONT = [
  79140. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79141. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79142. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79143. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79144. ];
  79145. PanoramaToCubeMapTools.FACE_BACK = [
  79146. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79147. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79148. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79149. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79150. ];
  79151. PanoramaToCubeMapTools.FACE_RIGHT = [
  79152. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79153. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79154. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79155. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79156. ];
  79157. PanoramaToCubeMapTools.FACE_LEFT = [
  79158. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79159. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79160. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79161. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79162. ];
  79163. PanoramaToCubeMapTools.FACE_DOWN = [
  79164. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79165. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79166. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79167. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79168. ];
  79169. PanoramaToCubeMapTools.FACE_UP = [
  79170. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79171. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79172. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79173. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79174. ];
  79175. return PanoramaToCubeMapTools;
  79176. }());
  79177. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79178. })(BABYLON || (BABYLON = {}));
  79179. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79180. var BABYLON;
  79181. (function (BABYLON) {
  79182. ;
  79183. /**
  79184. * This groups tools to convert HDR texture to native colors array.
  79185. */
  79186. var HDRTools = /** @class */ (function () {
  79187. function HDRTools() {
  79188. }
  79189. HDRTools.Ldexp = function (mantissa, exponent) {
  79190. if (exponent > 1023) {
  79191. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79192. }
  79193. if (exponent < -1074) {
  79194. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79195. }
  79196. return mantissa * Math.pow(2, exponent);
  79197. };
  79198. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79199. if (exponent > 0) { /*nonzero pixel*/
  79200. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79201. float32array[index + 0] = red * exponent;
  79202. float32array[index + 1] = green * exponent;
  79203. float32array[index + 2] = blue * exponent;
  79204. }
  79205. else {
  79206. float32array[index + 0] = 0;
  79207. float32array[index + 1] = 0;
  79208. float32array[index + 2] = 0;
  79209. }
  79210. };
  79211. HDRTools.readStringLine = function (uint8array, startIndex) {
  79212. var line = "";
  79213. var character = "";
  79214. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79215. character = String.fromCharCode(uint8array[i]);
  79216. if (character == "\n") {
  79217. break;
  79218. }
  79219. line += character;
  79220. }
  79221. return line;
  79222. };
  79223. /**
  79224. * Reads header information from an RGBE texture stored in a native array.
  79225. * More information on this format are available here:
  79226. * https://en.wikipedia.org/wiki/RGBE_image_format
  79227. *
  79228. * @param uint8array The binary file stored in native array.
  79229. * @return The header information.
  79230. */
  79231. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79232. var height = 0;
  79233. var width = 0;
  79234. var line = this.readStringLine(uint8array, 0);
  79235. if (line[0] != '#' || line[1] != '?') {
  79236. throw "Bad HDR Format.";
  79237. }
  79238. var endOfHeader = false;
  79239. var findFormat = false;
  79240. var lineIndex = 0;
  79241. do {
  79242. lineIndex += (line.length + 1);
  79243. line = this.readStringLine(uint8array, lineIndex);
  79244. if (line == "FORMAT=32-bit_rle_rgbe") {
  79245. findFormat = true;
  79246. }
  79247. else if (line.length == 0) {
  79248. endOfHeader = true;
  79249. }
  79250. } while (!endOfHeader);
  79251. if (!findFormat) {
  79252. throw "HDR Bad header format, unsupported FORMAT";
  79253. }
  79254. lineIndex += (line.length + 1);
  79255. line = this.readStringLine(uint8array, lineIndex);
  79256. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79257. var match = sizeRegexp.exec(line);
  79258. // TODO. Support +Y and -X if needed.
  79259. if (!match || match.length < 3) {
  79260. throw "HDR Bad header format, no size";
  79261. }
  79262. width = parseInt(match[2]);
  79263. height = parseInt(match[1]);
  79264. if (width < 8 || width > 0x7fff) {
  79265. throw "HDR Bad header format, unsupported size";
  79266. }
  79267. lineIndex += (line.length + 1);
  79268. return {
  79269. height: height,
  79270. width: width,
  79271. dataPosition: lineIndex
  79272. };
  79273. };
  79274. /**
  79275. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79276. * This RGBE texture needs to store the information as a panorama.
  79277. *
  79278. * More information on this format are available here:
  79279. * https://en.wikipedia.org/wiki/RGBE_image_format
  79280. *
  79281. * @param buffer The binary file stored in an array buffer.
  79282. * @param size The expected size of the extracted cubemap.
  79283. * @return The Cube Map information.
  79284. */
  79285. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79286. var uint8array = new Uint8Array(buffer);
  79287. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79288. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79289. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79290. return cubeMapData;
  79291. };
  79292. /**
  79293. * Returns the pixels data extracted from an RGBE texture.
  79294. * This pixels will be stored left to right up to down in the R G B order in one array.
  79295. *
  79296. * More information on this format are available here:
  79297. * https://en.wikipedia.org/wiki/RGBE_image_format
  79298. *
  79299. * @param uint8array The binary file stored in an array buffer.
  79300. * @param hdrInfo The header information of the file.
  79301. * @return The pixels data in RGB right to left up to down order.
  79302. */
  79303. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79304. // Keep for multi format supports.
  79305. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79306. };
  79307. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79308. var num_scanlines = hdrInfo.height;
  79309. var scanline_width = hdrInfo.width;
  79310. var a, b, c, d, count;
  79311. var dataIndex = hdrInfo.dataPosition;
  79312. var index = 0, endIndex = 0, i = 0;
  79313. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79314. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79315. // 3 channels of 4 bytes per pixel in float.
  79316. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79317. var resultArray = new Float32Array(resultBuffer);
  79318. // read in each successive scanline
  79319. while (num_scanlines > 0) {
  79320. a = uint8array[dataIndex++];
  79321. b = uint8array[dataIndex++];
  79322. c = uint8array[dataIndex++];
  79323. d = uint8array[dataIndex++];
  79324. if (a != 2 || b != 2 || (c & 0x80)) {
  79325. // this file is not run length encoded
  79326. throw "HDR Bad header format, not RLE";
  79327. }
  79328. if (((c << 8) | d) != scanline_width) {
  79329. throw "HDR Bad header format, wrong scan line width";
  79330. }
  79331. index = 0;
  79332. // read each of the four channels for the scanline into the buffer
  79333. for (i = 0; i < 4; i++) {
  79334. endIndex = (i + 1) * scanline_width;
  79335. while (index < endIndex) {
  79336. a = uint8array[dataIndex++];
  79337. b = uint8array[dataIndex++];
  79338. if (a > 128) {
  79339. // a run of the same value
  79340. count = a - 128;
  79341. if ((count == 0) || (count > endIndex - index)) {
  79342. throw "HDR Bad Format, bad scanline data (run)";
  79343. }
  79344. while (count-- > 0) {
  79345. scanLineArray[index++] = b;
  79346. }
  79347. }
  79348. else {
  79349. // a non-run
  79350. count = a;
  79351. if ((count == 0) || (count > endIndex - index)) {
  79352. throw "HDR Bad Format, bad scanline data (non-run)";
  79353. }
  79354. scanLineArray[index++] = b;
  79355. if (--count > 0) {
  79356. for (var j = 0; j < count; j++) {
  79357. scanLineArray[index++] = uint8array[dataIndex++];
  79358. }
  79359. }
  79360. }
  79361. }
  79362. }
  79363. // now convert data from buffer into floats
  79364. for (i = 0; i < scanline_width; i++) {
  79365. a = scanLineArray[i];
  79366. b = scanLineArray[i + scanline_width];
  79367. c = scanLineArray[i + 2 * scanline_width];
  79368. d = scanLineArray[i + 3 * scanline_width];
  79369. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79370. }
  79371. num_scanlines--;
  79372. }
  79373. return resultArray;
  79374. };
  79375. return HDRTools;
  79376. }());
  79377. BABYLON.HDRTools = HDRTools;
  79378. })(BABYLON || (BABYLON = {}));
  79379. //# sourceMappingURL=babylon.hdr.js.map
  79380. var BABYLON;
  79381. (function (BABYLON) {
  79382. /**
  79383. * This represents a texture coming from an HDR input.
  79384. *
  79385. * The only supported format is currently panorama picture stored in RGBE format.
  79386. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79387. */
  79388. var HDRCubeTexture = /** @class */ (function (_super) {
  79389. __extends(HDRCubeTexture, _super);
  79390. /**
  79391. * Instantiates an HDRTexture from the following parameters.
  79392. *
  79393. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  79394. * @param scene The scene the texture will be used in
  79395. * @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.
  79396. * @param noMipmap Forces to not generate the mipmap if true
  79397. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  79398. * @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)
  79399. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  79400. */
  79401. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  79402. if (noMipmap === void 0) { noMipmap = false; }
  79403. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79404. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79405. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79406. if (onLoad === void 0) { onLoad = null; }
  79407. if (onError === void 0) { onError = null; }
  79408. var _this = _super.call(this, scene) || this;
  79409. _this._useInGammaSpace = false;
  79410. _this._generateHarmonics = true;
  79411. _this._isBABYLONPreprocessed = false;
  79412. _this._onLoad = null;
  79413. _this._onError = null;
  79414. /**
  79415. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  79416. */
  79417. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  79418. /**
  79419. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  79420. * This is usefull at run time to apply the good shader.
  79421. */
  79422. _this.isPMREM = false;
  79423. _this._isBlocking = true;
  79424. _this._rotationY = 0;
  79425. /**
  79426. * Gets or sets the center of the bounding box associated with the cube texture
  79427. * It must define where the camera used to render the texture was set
  79428. */
  79429. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  79430. if (!url) {
  79431. return _this;
  79432. }
  79433. _this.name = url;
  79434. _this.url = url;
  79435. _this.hasAlpha = false;
  79436. _this.isCube = true;
  79437. _this._textureMatrix = BABYLON.Matrix.Identity();
  79438. _this._onLoad = onLoad;
  79439. _this._onError = onError;
  79440. _this.gammaSpace = false;
  79441. var caps = scene.getEngine().getCaps();
  79442. if (size) {
  79443. _this._isBABYLONPreprocessed = false;
  79444. _this._noMipmap = noMipmap;
  79445. _this._size = size;
  79446. _this._useInGammaSpace = useInGammaSpace;
  79447. _this._usePMREMGenerator = usePMREMGenerator &&
  79448. caps.textureLOD &&
  79449. caps.textureFloat &&
  79450. !_this._useInGammaSpace;
  79451. }
  79452. else {
  79453. _this._isBABYLONPreprocessed = true;
  79454. _this._noMipmap = false;
  79455. _this._useInGammaSpace = false;
  79456. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  79457. !_this._useInGammaSpace;
  79458. }
  79459. _this.isPMREM = _this._usePMREMGenerator;
  79460. _this._texture = _this._getFromCache(url, _this._noMipmap);
  79461. if (!_this._texture) {
  79462. if (!scene.useDelayedTextureLoading) {
  79463. _this.loadTexture();
  79464. }
  79465. else {
  79466. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79467. }
  79468. }
  79469. return _this;
  79470. }
  79471. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  79472. /**
  79473. * Gets wether or not the texture is blocking during loading.
  79474. */
  79475. get: function () {
  79476. return this._isBlocking;
  79477. },
  79478. /**
  79479. * Sets wether or not the texture is blocking during loading.
  79480. */
  79481. set: function (value) {
  79482. this._isBlocking = value;
  79483. },
  79484. enumerable: true,
  79485. configurable: true
  79486. });
  79487. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  79488. /**
  79489. * Gets texture matrix rotation angle around Y axis radians.
  79490. */
  79491. get: function () {
  79492. return this._rotationY;
  79493. },
  79494. /**
  79495. * Sets texture matrix rotation angle around Y axis in radians.
  79496. */
  79497. set: function (value) {
  79498. this._rotationY = value;
  79499. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  79500. },
  79501. enumerable: true,
  79502. configurable: true
  79503. });
  79504. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  79505. get: function () {
  79506. return this._boundingBoxSize;
  79507. },
  79508. /**
  79509. * Gets or sets the size of the bounding box associated with the cube texture
  79510. * When defined, the cubemap will switch to local mode
  79511. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  79512. * @example https://www.babylonjs-playground.com/#RNASML
  79513. */
  79514. set: function (value) {
  79515. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  79516. return;
  79517. }
  79518. this._boundingBoxSize = value;
  79519. var scene = this.getScene();
  79520. if (scene) {
  79521. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  79522. }
  79523. },
  79524. enumerable: true,
  79525. configurable: true
  79526. });
  79527. /**
  79528. * Occurs when the file is a preprocessed .babylon.hdr file.
  79529. */
  79530. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  79531. var _this = this;
  79532. var mipLevels = 0;
  79533. var floatArrayView = null;
  79534. var scene = this.getScene();
  79535. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  79536. var mips = new Array();
  79537. if (!floatArrayView) {
  79538. return mips;
  79539. }
  79540. var startIndex = 30;
  79541. for (var level = 0; level < mipLevels; level++) {
  79542. mips.push([]);
  79543. // Fill each pixel of the mip level.
  79544. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  79545. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79546. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  79547. mips[level].push(faceData);
  79548. startIndex += faceSize;
  79549. }
  79550. }
  79551. return mips;
  79552. } : null;
  79553. var callback = function (buffer) {
  79554. var scene = _this.getScene();
  79555. if (!scene) {
  79556. return null;
  79557. }
  79558. // Create Native Array Views
  79559. var intArrayView = new Int32Array(buffer);
  79560. floatArrayView = new Float32Array(buffer);
  79561. // Fill header.
  79562. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  79563. _this._size = intArrayView[1]; // CubeMap max mip face size.
  79564. // Update Texture Information.
  79565. if (!_this._texture) {
  79566. return null;
  79567. }
  79568. _this._texture.updateSize(_this._size, _this._size);
  79569. // Fill polynomial information.
  79570. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  79571. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  79572. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  79573. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  79574. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  79575. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  79576. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  79577. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  79578. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  79579. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  79580. _this.sphericalPolynomial = sphericalPolynomial;
  79581. // Fill pixel data.
  79582. mipLevels = intArrayView[29]; // Number of mip levels.
  79583. var startIndex = 30;
  79584. var data = [];
  79585. var faceSize = Math.pow(_this._size, 2) * 3;
  79586. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79587. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79588. startIndex += faceSize;
  79589. }
  79590. var results = [];
  79591. var byteArray = null;
  79592. // Push each faces.
  79593. for (var k = 0; k < 6; k++) {
  79594. var dataFace = null;
  79595. // To be deprecated.
  79596. if (version === 1) {
  79597. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79598. dataFace = data[j];
  79599. }
  79600. // If special cases.
  79601. if (!mipmapGenerator && dataFace) {
  79602. if (!scene.getEngine().getCaps().textureFloat) {
  79603. // 3 channels of 1 bytes per pixel in bytes.
  79604. var byteBuffer = new ArrayBuffer(faceSize);
  79605. byteArray = new Uint8Array(byteBuffer);
  79606. }
  79607. for (var i = 0; i < _this._size * _this._size; i++) {
  79608. // Put in gamma space if requested.
  79609. if (_this._useInGammaSpace) {
  79610. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79611. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79612. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79613. }
  79614. // Convert to int texture for fallback.
  79615. if (byteArray) {
  79616. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79617. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79618. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79619. // May use luminance instead if the result is not accurate.
  79620. var max = Math.max(Math.max(r, g), b);
  79621. if (max > 255) {
  79622. var scale = 255 / max;
  79623. r *= scale;
  79624. g *= scale;
  79625. b *= scale;
  79626. }
  79627. byteArray[(i * 3) + 0] = r;
  79628. byteArray[(i * 3) + 1] = g;
  79629. byteArray[(i * 3) + 2] = b;
  79630. }
  79631. }
  79632. }
  79633. // Fill the array accordingly.
  79634. if (byteArray) {
  79635. results.push(byteArray);
  79636. }
  79637. else {
  79638. results.push(dataFace);
  79639. }
  79640. }
  79641. return results;
  79642. };
  79643. if (scene) {
  79644. 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);
  79645. }
  79646. };
  79647. /**
  79648. * Occurs when the file is raw .hdr file.
  79649. */
  79650. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79651. var _this = this;
  79652. var callback = function (buffer) {
  79653. var scene = _this.getScene();
  79654. if (!scene) {
  79655. return null;
  79656. }
  79657. // Extract the raw linear data.
  79658. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79659. // Generate harmonics if needed.
  79660. if (_this._generateHarmonics) {
  79661. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79662. _this.sphericalPolynomial = sphericalPolynomial;
  79663. }
  79664. var results = [];
  79665. var byteArray = null;
  79666. // Push each faces.
  79667. for (var j = 0; j < 6; j++) {
  79668. // Create uintarray fallback.
  79669. if (!scene.getEngine().getCaps().textureFloat) {
  79670. // 3 channels of 1 bytes per pixel in bytes.
  79671. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79672. byteArray = new Uint8Array(byteBuffer);
  79673. }
  79674. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79675. // If special cases.
  79676. if (_this._useInGammaSpace || byteArray) {
  79677. for (var i = 0; i < _this._size * _this._size; i++) {
  79678. // Put in gamma space if requested.
  79679. if (_this._useInGammaSpace) {
  79680. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79681. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79682. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79683. }
  79684. // Convert to int texture for fallback.
  79685. if (byteArray) {
  79686. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79687. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79688. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79689. // May use luminance instead if the result is not accurate.
  79690. var max = Math.max(Math.max(r, g), b);
  79691. if (max > 255) {
  79692. var scale = 255 / max;
  79693. r *= scale;
  79694. g *= scale;
  79695. b *= scale;
  79696. }
  79697. byteArray[(i * 3) + 0] = r;
  79698. byteArray[(i * 3) + 1] = g;
  79699. byteArray[(i * 3) + 2] = b;
  79700. }
  79701. }
  79702. }
  79703. if (byteArray) {
  79704. results.push(byteArray);
  79705. }
  79706. else {
  79707. results.push(dataFace);
  79708. }
  79709. }
  79710. return results;
  79711. };
  79712. var mipmapGenerator = null;
  79713. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79714. // if (!this._noMipmap &&
  79715. // this._usePMREMGenerator) {
  79716. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79717. // // Custom setup of the generator matching with the PBR shader values.
  79718. // var generator = new BABYLON.PMREMGenerator(data,
  79719. // this._size,
  79720. // this._size,
  79721. // 0,
  79722. // 3,
  79723. // this.getScene().getEngine().getCaps().textureFloat,
  79724. // 2048,
  79725. // 0.25,
  79726. // false,
  79727. // true);
  79728. // return generator.filterCubeMap();
  79729. // };
  79730. // }
  79731. var scene = this.getScene();
  79732. if (scene) {
  79733. 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);
  79734. }
  79735. };
  79736. /**
  79737. * Starts the loading process of the texture.
  79738. */
  79739. HDRCubeTexture.prototype.loadTexture = function () {
  79740. if (this._isBABYLONPreprocessed) {
  79741. this.loadBabylonTexture();
  79742. }
  79743. else {
  79744. this.loadHDRTexture();
  79745. }
  79746. };
  79747. HDRCubeTexture.prototype.clone = function () {
  79748. var scene = this.getScene();
  79749. if (!scene) {
  79750. return this;
  79751. }
  79752. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79753. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79754. // Base texture
  79755. newTexture.level = this.level;
  79756. newTexture.wrapU = this.wrapU;
  79757. newTexture.wrapV = this.wrapV;
  79758. newTexture.coordinatesIndex = this.coordinatesIndex;
  79759. newTexture.coordinatesMode = this.coordinatesMode;
  79760. return newTexture;
  79761. };
  79762. // Methods
  79763. HDRCubeTexture.prototype.delayLoad = function () {
  79764. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79765. return;
  79766. }
  79767. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79768. this._texture = this._getFromCache(this.url, this._noMipmap);
  79769. if (!this._texture) {
  79770. this.loadTexture();
  79771. }
  79772. };
  79773. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79774. return this._textureMatrix;
  79775. };
  79776. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79777. this._textureMatrix = value;
  79778. };
  79779. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79780. var texture = null;
  79781. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79782. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79783. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79784. texture.name = parsedTexture.name;
  79785. texture.hasAlpha = parsedTexture.hasAlpha;
  79786. texture.level = parsedTexture.level;
  79787. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79788. texture.isBlocking = parsedTexture.isBlocking;
  79789. }
  79790. if (texture) {
  79791. if (parsedTexture.boundingBoxPosition) {
  79792. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79793. }
  79794. if (parsedTexture.boundingBoxSize) {
  79795. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79796. }
  79797. if (parsedTexture.rotationY) {
  79798. texture.rotationY = parsedTexture.rotationY;
  79799. }
  79800. }
  79801. return texture;
  79802. };
  79803. HDRCubeTexture.prototype.serialize = function () {
  79804. if (!this.name) {
  79805. return null;
  79806. }
  79807. var serializationObject = {};
  79808. serializationObject.name = this.name;
  79809. serializationObject.hasAlpha = this.hasAlpha;
  79810. serializationObject.isCube = true;
  79811. serializationObject.level = this.level;
  79812. serializationObject.size = this._size;
  79813. serializationObject.coordinatesMode = this.coordinatesMode;
  79814. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79815. serializationObject.generateHarmonics = this._generateHarmonics;
  79816. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79817. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79818. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79819. serializationObject.noMipmap = this._noMipmap;
  79820. serializationObject.isBlocking = this._isBlocking;
  79821. serializationObject.rotationY = this._rotationY;
  79822. return serializationObject;
  79823. };
  79824. /**
  79825. * Saves as a file the data contained in the texture in a binary format.
  79826. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79827. * as the spherical used in the lighting.
  79828. * @param url The HDR file url.
  79829. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79830. * @param onError Method called if any error happens during download.
  79831. * @return The packed binary data.
  79832. */
  79833. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79834. if (onError === void 0) { onError = null; }
  79835. var callback = function (buffer) {
  79836. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79837. // Returns a URL you can use as a href.
  79838. var objUrl = window.URL.createObjectURL(data);
  79839. // Simulates a link to it and click to dowload.
  79840. var a = document.createElement("a");
  79841. document.body.appendChild(a);
  79842. a.style.display = "none";
  79843. a.href = objUrl;
  79844. a.download = "envmap.babylon.hdr";
  79845. a.click();
  79846. };
  79847. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  79848. };
  79849. /**
  79850. * Serializes the data contained in the texture in a binary format.
  79851. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79852. * as the spherical used in the lighting.
  79853. * @param url The HDR file url.
  79854. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79855. * @param onError Method called if any error happens during download.
  79856. * @return The packed binary data.
  79857. */
  79858. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  79859. if (onError === void 0) { onError = null; }
  79860. // Needs the url tho create the texture.
  79861. if (!url) {
  79862. return;
  79863. }
  79864. // Check Power of two size.
  79865. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  79866. return;
  79867. }
  79868. // Coming Back in 3.x.
  79869. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  79870. };
  79871. HDRCubeTexture._facesMapping = [
  79872. "right",
  79873. "left",
  79874. "up",
  79875. "down",
  79876. "front",
  79877. "back"
  79878. ];
  79879. return HDRCubeTexture;
  79880. }(BABYLON.BaseTexture));
  79881. BABYLON.HDRCubeTexture = HDRCubeTexture;
  79882. })(BABYLON || (BABYLON = {}));
  79883. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  79884. var BABYLON;
  79885. (function (BABYLON) {
  79886. var IndexedVector2 = /** @class */ (function (_super) {
  79887. __extends(IndexedVector2, _super);
  79888. function IndexedVector2(original, index) {
  79889. var _this = _super.call(this, original.x, original.y) || this;
  79890. _this.index = index;
  79891. return _this;
  79892. }
  79893. return IndexedVector2;
  79894. }(BABYLON.Vector2));
  79895. var PolygonPoints = /** @class */ (function () {
  79896. function PolygonPoints() {
  79897. this.elements = new Array();
  79898. }
  79899. PolygonPoints.prototype.add = function (originalPoints) {
  79900. var _this = this;
  79901. var result = new Array();
  79902. originalPoints.forEach(function (point) {
  79903. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  79904. var newPoint = new IndexedVector2(point, _this.elements.length);
  79905. result.push(newPoint);
  79906. _this.elements.push(newPoint);
  79907. }
  79908. });
  79909. return result;
  79910. };
  79911. PolygonPoints.prototype.computeBounds = function () {
  79912. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79913. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  79914. this.elements.forEach(function (point) {
  79915. // x
  79916. if (point.x < lmin.x) {
  79917. lmin.x = point.x;
  79918. }
  79919. else if (point.x > lmax.x) {
  79920. lmax.x = point.x;
  79921. }
  79922. // y
  79923. if (point.y < lmin.y) {
  79924. lmin.y = point.y;
  79925. }
  79926. else if (point.y > lmax.y) {
  79927. lmax.y = point.y;
  79928. }
  79929. });
  79930. return {
  79931. min: lmin,
  79932. max: lmax,
  79933. width: lmax.x - lmin.x,
  79934. height: lmax.y - lmin.y
  79935. };
  79936. };
  79937. return PolygonPoints;
  79938. }());
  79939. var Polygon = /** @class */ (function () {
  79940. function Polygon() {
  79941. }
  79942. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  79943. return [
  79944. new BABYLON.Vector2(xmin, ymin),
  79945. new BABYLON.Vector2(xmax, ymin),
  79946. new BABYLON.Vector2(xmax, ymax),
  79947. new BABYLON.Vector2(xmin, ymax)
  79948. ];
  79949. };
  79950. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  79951. if (cx === void 0) { cx = 0; }
  79952. if (cy === void 0) { cy = 0; }
  79953. if (numberOfSides === void 0) { numberOfSides = 32; }
  79954. var result = new Array();
  79955. var angle = 0;
  79956. var increment = (Math.PI * 2) / numberOfSides;
  79957. for (var i = 0; i < numberOfSides; i++) {
  79958. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  79959. angle -= increment;
  79960. }
  79961. return result;
  79962. };
  79963. Polygon.Parse = function (input) {
  79964. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  79965. var i, result = [];
  79966. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  79967. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  79968. }
  79969. return result;
  79970. };
  79971. Polygon.StartingAt = function (x, y) {
  79972. return BABYLON.Path2.StartingAt(x, y);
  79973. };
  79974. return Polygon;
  79975. }());
  79976. BABYLON.Polygon = Polygon;
  79977. var PolygonMeshBuilder = /** @class */ (function () {
  79978. function PolygonMeshBuilder(name, contours, scene) {
  79979. this._points = new PolygonPoints();
  79980. this._outlinepoints = new PolygonPoints();
  79981. this._holes = new Array();
  79982. this._epoints = new Array();
  79983. this._eholes = new Array();
  79984. this._name = name;
  79985. this._scene = scene;
  79986. var points;
  79987. if (contours instanceof BABYLON.Path2) {
  79988. points = contours.getPoints();
  79989. }
  79990. else {
  79991. points = contours;
  79992. }
  79993. this._addToepoint(points);
  79994. this._points.add(points);
  79995. this._outlinepoints.add(points);
  79996. if (typeof earcut === 'undefined') {
  79997. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  79998. }
  79999. }
  80000. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80001. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80002. var p = points_1[_i];
  80003. this._epoints.push(p.x, p.y);
  80004. }
  80005. };
  80006. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80007. this._points.add(hole);
  80008. var holepoints = new PolygonPoints();
  80009. holepoints.add(hole);
  80010. this._holes.push(holepoints);
  80011. this._eholes.push(this._epoints.length / 2);
  80012. this._addToepoint(hole);
  80013. return this;
  80014. };
  80015. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80016. var _this = this;
  80017. if (updatable === void 0) { updatable = false; }
  80018. if (depth === void 0) { depth = 0; }
  80019. var result = new BABYLON.Mesh(this._name, this._scene);
  80020. var normals = new Array();
  80021. var positions = new Array();
  80022. var uvs = new Array();
  80023. var bounds = this._points.computeBounds();
  80024. this._points.elements.forEach(function (p) {
  80025. normals.push(0, 1.0, 0);
  80026. positions.push(p.x, 0, p.y);
  80027. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80028. });
  80029. var indices = new Array();
  80030. var res = earcut(this._epoints, this._eholes, 2);
  80031. for (var i = 0; i < res.length; i++) {
  80032. indices.push(res[i]);
  80033. }
  80034. if (depth > 0) {
  80035. var positionscount = (positions.length / 3); //get the current pointcount
  80036. this._points.elements.forEach(function (p) {
  80037. normals.push(0, -1.0, 0);
  80038. positions.push(p.x, -depth, p.y);
  80039. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80040. });
  80041. var totalCount = indices.length;
  80042. for (var i = 0; i < totalCount; i += 3) {
  80043. var i0 = indices[i + 0];
  80044. var i1 = indices[i + 1];
  80045. var i2 = indices[i + 2];
  80046. indices.push(i2 + positionscount);
  80047. indices.push(i1 + positionscount);
  80048. indices.push(i0 + positionscount);
  80049. }
  80050. //Add the sides
  80051. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80052. this._holes.forEach(function (hole) {
  80053. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80054. });
  80055. }
  80056. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80057. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80058. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80059. result.setIndices(indices);
  80060. return result;
  80061. };
  80062. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80063. var StartIndex = positions.length / 3;
  80064. var ulength = 0;
  80065. for (var i = 0; i < points.elements.length; i++) {
  80066. var p = points.elements[i];
  80067. var p1;
  80068. if ((i + 1) > points.elements.length - 1) {
  80069. p1 = points.elements[0];
  80070. }
  80071. else {
  80072. p1 = points.elements[i + 1];
  80073. }
  80074. positions.push(p.x, 0, p.y);
  80075. positions.push(p.x, -depth, p.y);
  80076. positions.push(p1.x, 0, p1.y);
  80077. positions.push(p1.x, -depth, p1.y);
  80078. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80079. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80080. var v3 = v2.subtract(v1);
  80081. var v4 = new BABYLON.Vector3(0, 1, 0);
  80082. var vn = BABYLON.Vector3.Cross(v3, v4);
  80083. vn = vn.normalize();
  80084. uvs.push(ulength / bounds.width, 0);
  80085. uvs.push(ulength / bounds.width, 1);
  80086. ulength += v3.length();
  80087. uvs.push((ulength / bounds.width), 0);
  80088. uvs.push((ulength / bounds.width), 1);
  80089. if (!flip) {
  80090. normals.push(-vn.x, -vn.y, -vn.z);
  80091. normals.push(-vn.x, -vn.y, -vn.z);
  80092. normals.push(-vn.x, -vn.y, -vn.z);
  80093. normals.push(-vn.x, -vn.y, -vn.z);
  80094. indices.push(StartIndex);
  80095. indices.push(StartIndex + 1);
  80096. indices.push(StartIndex + 2);
  80097. indices.push(StartIndex + 1);
  80098. indices.push(StartIndex + 3);
  80099. indices.push(StartIndex + 2);
  80100. }
  80101. else {
  80102. normals.push(vn.x, vn.y, vn.z);
  80103. normals.push(vn.x, vn.y, vn.z);
  80104. normals.push(vn.x, vn.y, vn.z);
  80105. normals.push(vn.x, vn.y, vn.z);
  80106. indices.push(StartIndex);
  80107. indices.push(StartIndex + 2);
  80108. indices.push(StartIndex + 1);
  80109. indices.push(StartIndex + 1);
  80110. indices.push(StartIndex + 2);
  80111. indices.push(StartIndex + 3);
  80112. }
  80113. StartIndex += 4;
  80114. }
  80115. ;
  80116. };
  80117. return PolygonMeshBuilder;
  80118. }());
  80119. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80120. })(BABYLON || (BABYLON = {}));
  80121. //# sourceMappingURL=babylon.polygonMesh.js.map
  80122. var BABYLON;
  80123. (function (BABYLON) {
  80124. // Unique ID when we import meshes from Babylon to CSG
  80125. var currentCSGMeshId = 0;
  80126. // # class Vertex
  80127. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80128. // one to provide additional features like texture coordinates and vertex
  80129. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80130. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80131. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80132. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80133. // is not used anywhere else.
  80134. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80135. var Vertex = /** @class */ (function () {
  80136. function Vertex(pos, normal, uv) {
  80137. this.pos = pos;
  80138. this.normal = normal;
  80139. this.uv = uv;
  80140. }
  80141. Vertex.prototype.clone = function () {
  80142. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80143. };
  80144. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80145. // orientation of a polygon is flipped.
  80146. Vertex.prototype.flip = function () {
  80147. this.normal = this.normal.scale(-1);
  80148. };
  80149. // Create a new vertex between this vertex and `other` by linearly
  80150. // interpolating all properties using a parameter of `t`. Subclasses should
  80151. // override this to interpolate additional properties.
  80152. Vertex.prototype.interpolate = function (other, t) {
  80153. 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));
  80154. };
  80155. return Vertex;
  80156. }());
  80157. // # class Plane
  80158. // Represents a plane in 3D space.
  80159. var Plane = /** @class */ (function () {
  80160. function Plane(normal, w) {
  80161. this.normal = normal;
  80162. this.w = w;
  80163. }
  80164. Plane.FromPoints = function (a, b, c) {
  80165. var v0 = c.subtract(a);
  80166. var v1 = b.subtract(a);
  80167. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80168. return null;
  80169. }
  80170. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80171. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80172. };
  80173. Plane.prototype.clone = function () {
  80174. return new Plane(this.normal.clone(), this.w);
  80175. };
  80176. Plane.prototype.flip = function () {
  80177. this.normal.scaleInPlace(-1);
  80178. this.w = -this.w;
  80179. };
  80180. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80181. // fragments in the appropriate lists. Coplanar polygons go into either
  80182. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80183. // respect to this plane. Polygons in front or in back of this plane go into
  80184. // either `front` or `back`.
  80185. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80186. var COPLANAR = 0;
  80187. var FRONT = 1;
  80188. var BACK = 2;
  80189. var SPANNING = 3;
  80190. // Classify each point as well as the entire polygon into one of the above
  80191. // four classes.
  80192. var polygonType = 0;
  80193. var types = [];
  80194. var i;
  80195. var t;
  80196. for (i = 0; i < polygon.vertices.length; i++) {
  80197. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80198. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80199. polygonType |= type;
  80200. types.push(type);
  80201. }
  80202. // Put the polygon in the correct list, splitting it when necessary.
  80203. switch (polygonType) {
  80204. case COPLANAR:
  80205. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80206. break;
  80207. case FRONT:
  80208. front.push(polygon);
  80209. break;
  80210. case BACK:
  80211. back.push(polygon);
  80212. break;
  80213. case SPANNING:
  80214. var f = [], b = [];
  80215. for (i = 0; i < polygon.vertices.length; i++) {
  80216. var j = (i + 1) % polygon.vertices.length;
  80217. var ti = types[i], tj = types[j];
  80218. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80219. if (ti !== BACK)
  80220. f.push(vi);
  80221. if (ti !== FRONT)
  80222. b.push(ti !== BACK ? vi.clone() : vi);
  80223. if ((ti | tj) === SPANNING) {
  80224. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80225. var v = vi.interpolate(vj, t);
  80226. f.push(v);
  80227. b.push(v.clone());
  80228. }
  80229. }
  80230. var poly;
  80231. if (f.length >= 3) {
  80232. poly = new Polygon(f, polygon.shared);
  80233. if (poly.plane)
  80234. front.push(poly);
  80235. }
  80236. if (b.length >= 3) {
  80237. poly = new Polygon(b, polygon.shared);
  80238. if (poly.plane)
  80239. back.push(poly);
  80240. }
  80241. break;
  80242. }
  80243. };
  80244. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80245. // point is on the plane.
  80246. Plane.EPSILON = 1e-5;
  80247. return Plane;
  80248. }());
  80249. // # class Polygon
  80250. // Represents a convex polygon. The vertices used to initialize a polygon must
  80251. // be coplanar and form a convex loop.
  80252. //
  80253. // Each convex polygon has a `shared` property, which is shared between all
  80254. // polygons that are clones of each other or were split from the same polygon.
  80255. // This can be used to define per-polygon properties (such as surface color).
  80256. var Polygon = /** @class */ (function () {
  80257. function Polygon(vertices, shared) {
  80258. this.vertices = vertices;
  80259. this.shared = shared;
  80260. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80261. }
  80262. Polygon.prototype.clone = function () {
  80263. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80264. return new Polygon(vertices, this.shared);
  80265. };
  80266. Polygon.prototype.flip = function () {
  80267. this.vertices.reverse().map(function (v) { v.flip(); });
  80268. this.plane.flip();
  80269. };
  80270. return Polygon;
  80271. }());
  80272. // # class Node
  80273. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80274. // by picking a polygon to split along. That polygon (and all other coplanar
  80275. // polygons) are added directly to that node and the other polygons are added to
  80276. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80277. // no distinction between internal and leaf nodes.
  80278. var Node = /** @class */ (function () {
  80279. function Node(polygons) {
  80280. this.plane = null;
  80281. this.front = null;
  80282. this.back = null;
  80283. this.polygons = new Array();
  80284. if (polygons) {
  80285. this.build(polygons);
  80286. }
  80287. }
  80288. Node.prototype.clone = function () {
  80289. var node = new Node();
  80290. node.plane = this.plane && this.plane.clone();
  80291. node.front = this.front && this.front.clone();
  80292. node.back = this.back && this.back.clone();
  80293. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80294. return node;
  80295. };
  80296. // Convert solid space to empty space and empty space to solid space.
  80297. Node.prototype.invert = function () {
  80298. for (var i = 0; i < this.polygons.length; i++) {
  80299. this.polygons[i].flip();
  80300. }
  80301. if (this.plane) {
  80302. this.plane.flip();
  80303. }
  80304. if (this.front) {
  80305. this.front.invert();
  80306. }
  80307. if (this.back) {
  80308. this.back.invert();
  80309. }
  80310. var temp = this.front;
  80311. this.front = this.back;
  80312. this.back = temp;
  80313. };
  80314. // Recursively remove all polygons in `polygons` that are inside this BSP
  80315. // tree.
  80316. Node.prototype.clipPolygons = function (polygons) {
  80317. if (!this.plane)
  80318. return polygons.slice();
  80319. var front = new Array(), back = new Array();
  80320. for (var i = 0; i < polygons.length; i++) {
  80321. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80322. }
  80323. if (this.front) {
  80324. front = this.front.clipPolygons(front);
  80325. }
  80326. if (this.back) {
  80327. back = this.back.clipPolygons(back);
  80328. }
  80329. else {
  80330. back = [];
  80331. }
  80332. return front.concat(back);
  80333. };
  80334. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80335. // `bsp`.
  80336. Node.prototype.clipTo = function (bsp) {
  80337. this.polygons = bsp.clipPolygons(this.polygons);
  80338. if (this.front)
  80339. this.front.clipTo(bsp);
  80340. if (this.back)
  80341. this.back.clipTo(bsp);
  80342. };
  80343. // Return a list of all polygons in this BSP tree.
  80344. Node.prototype.allPolygons = function () {
  80345. var polygons = this.polygons.slice();
  80346. if (this.front)
  80347. polygons = polygons.concat(this.front.allPolygons());
  80348. if (this.back)
  80349. polygons = polygons.concat(this.back.allPolygons());
  80350. return polygons;
  80351. };
  80352. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80353. // new polygons are filtered down to the bottom of the tree and become new
  80354. // nodes there. Each set of polygons is partitioned using the first polygon
  80355. // (no heuristic is used to pick a good split).
  80356. Node.prototype.build = function (polygons) {
  80357. if (!polygons.length)
  80358. return;
  80359. if (!this.plane)
  80360. this.plane = polygons[0].plane.clone();
  80361. var front = new Array(), back = new Array();
  80362. for (var i = 0; i < polygons.length; i++) {
  80363. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80364. }
  80365. if (front.length) {
  80366. if (!this.front)
  80367. this.front = new Node();
  80368. this.front.build(front);
  80369. }
  80370. if (back.length) {
  80371. if (!this.back)
  80372. this.back = new Node();
  80373. this.back.build(back);
  80374. }
  80375. };
  80376. return Node;
  80377. }());
  80378. var CSG = /** @class */ (function () {
  80379. function CSG() {
  80380. this.polygons = new Array();
  80381. }
  80382. // Convert BABYLON.Mesh to BABYLON.CSG
  80383. CSG.FromMesh = function (mesh) {
  80384. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80385. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80386. if (mesh instanceof BABYLON.Mesh) {
  80387. mesh.computeWorldMatrix(true);
  80388. matrix = mesh.getWorldMatrix();
  80389. meshPosition = mesh.position.clone();
  80390. meshRotation = mesh.rotation.clone();
  80391. if (mesh.rotationQuaternion) {
  80392. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80393. }
  80394. meshScaling = mesh.scaling.clone();
  80395. }
  80396. else {
  80397. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80398. }
  80399. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80400. var subMeshes = mesh.subMeshes;
  80401. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80402. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80403. vertices = [];
  80404. for (var j = 0; j < 3; j++) {
  80405. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80406. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80407. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80408. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80409. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80410. vertex = new Vertex(position, normal, uv);
  80411. vertices.push(vertex);
  80412. }
  80413. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80414. // To handle the case of degenerated triangle
  80415. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80416. if (polygon.plane)
  80417. polygons.push(polygon);
  80418. }
  80419. }
  80420. var csg = CSG.FromPolygons(polygons);
  80421. csg.matrix = matrix;
  80422. csg.position = meshPosition;
  80423. csg.rotation = meshRotation;
  80424. csg.scaling = meshScaling;
  80425. csg.rotationQuaternion = meshRotationQuaternion;
  80426. currentCSGMeshId++;
  80427. return csg;
  80428. };
  80429. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80430. CSG.FromPolygons = function (polygons) {
  80431. var csg = new CSG();
  80432. csg.polygons = polygons;
  80433. return csg;
  80434. };
  80435. CSG.prototype.clone = function () {
  80436. var csg = new CSG();
  80437. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80438. csg.copyTransformAttributes(this);
  80439. return csg;
  80440. };
  80441. CSG.prototype.union = function (csg) {
  80442. var a = new Node(this.clone().polygons);
  80443. var b = new Node(csg.clone().polygons);
  80444. a.clipTo(b);
  80445. b.clipTo(a);
  80446. b.invert();
  80447. b.clipTo(a);
  80448. b.invert();
  80449. a.build(b.allPolygons());
  80450. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80451. };
  80452. CSG.prototype.unionInPlace = function (csg) {
  80453. var a = new Node(this.polygons);
  80454. var b = new Node(csg.polygons);
  80455. a.clipTo(b);
  80456. b.clipTo(a);
  80457. b.invert();
  80458. b.clipTo(a);
  80459. b.invert();
  80460. a.build(b.allPolygons());
  80461. this.polygons = a.allPolygons();
  80462. };
  80463. CSG.prototype.subtract = function (csg) {
  80464. var a = new Node(this.clone().polygons);
  80465. var b = new Node(csg.clone().polygons);
  80466. a.invert();
  80467. a.clipTo(b);
  80468. b.clipTo(a);
  80469. b.invert();
  80470. b.clipTo(a);
  80471. b.invert();
  80472. a.build(b.allPolygons());
  80473. a.invert();
  80474. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80475. };
  80476. CSG.prototype.subtractInPlace = function (csg) {
  80477. var a = new Node(this.polygons);
  80478. var b = new Node(csg.polygons);
  80479. a.invert();
  80480. a.clipTo(b);
  80481. b.clipTo(a);
  80482. b.invert();
  80483. b.clipTo(a);
  80484. b.invert();
  80485. a.build(b.allPolygons());
  80486. a.invert();
  80487. this.polygons = a.allPolygons();
  80488. };
  80489. CSG.prototype.intersect = function (csg) {
  80490. var a = new Node(this.clone().polygons);
  80491. var b = new Node(csg.clone().polygons);
  80492. a.invert();
  80493. b.clipTo(a);
  80494. b.invert();
  80495. a.clipTo(b);
  80496. b.clipTo(a);
  80497. a.build(b.allPolygons());
  80498. a.invert();
  80499. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80500. };
  80501. CSG.prototype.intersectInPlace = function (csg) {
  80502. var a = new Node(this.polygons);
  80503. var b = new Node(csg.polygons);
  80504. a.invert();
  80505. b.clipTo(a);
  80506. b.invert();
  80507. a.clipTo(b);
  80508. b.clipTo(a);
  80509. a.build(b.allPolygons());
  80510. a.invert();
  80511. this.polygons = a.allPolygons();
  80512. };
  80513. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80514. // not modified.
  80515. CSG.prototype.inverse = function () {
  80516. var csg = this.clone();
  80517. csg.inverseInPlace();
  80518. return csg;
  80519. };
  80520. CSG.prototype.inverseInPlace = function () {
  80521. this.polygons.map(function (p) { p.flip(); });
  80522. };
  80523. // This is used to keep meshes transformations so they can be restored
  80524. // when we build back a Babylon Mesh
  80525. // NB : All CSG operations are performed in world coordinates
  80526. CSG.prototype.copyTransformAttributes = function (csg) {
  80527. this.matrix = csg.matrix;
  80528. this.position = csg.position;
  80529. this.rotation = csg.rotation;
  80530. this.scaling = csg.scaling;
  80531. this.rotationQuaternion = csg.rotationQuaternion;
  80532. return this;
  80533. };
  80534. // Build Raw mesh from CSG
  80535. // Coordinates here are in world space
  80536. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80537. var matrix = this.matrix.clone();
  80538. matrix.invert();
  80539. 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;
  80540. if (keepSubMeshes) {
  80541. // Sort Polygons, since subMeshes are indices range
  80542. polygons.sort(function (a, b) {
  80543. if (a.shared.meshId === b.shared.meshId) {
  80544. return a.shared.subMeshId - b.shared.subMeshId;
  80545. }
  80546. else {
  80547. return a.shared.meshId - b.shared.meshId;
  80548. }
  80549. });
  80550. }
  80551. for (var i = 0, il = polygons.length; i < il; i++) {
  80552. polygon = polygons[i];
  80553. // Building SubMeshes
  80554. if (!subMesh_dict[polygon.shared.meshId]) {
  80555. subMesh_dict[polygon.shared.meshId] = {};
  80556. }
  80557. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  80558. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  80559. indexStart: +Infinity,
  80560. indexEnd: -Infinity,
  80561. materialIndex: polygon.shared.materialIndex
  80562. };
  80563. }
  80564. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  80565. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  80566. polygonIndices[0] = 0;
  80567. polygonIndices[1] = j - 1;
  80568. polygonIndices[2] = j;
  80569. for (var k = 0; k < 3; k++) {
  80570. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  80571. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  80572. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  80573. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  80574. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  80575. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  80576. // Check if 2 points can be merged
  80577. if (!(typeof vertex_idx !== 'undefined' &&
  80578. normals[vertex_idx * 3] === localNormal.x &&
  80579. normals[vertex_idx * 3 + 1] === localNormal.y &&
  80580. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80581. uvs[vertex_idx * 2] === uv.x &&
  80582. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80583. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80584. uvs.push(uv.x, uv.y);
  80585. normals.push(normal.x, normal.y, normal.z);
  80586. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80587. }
  80588. indices.push(vertex_idx);
  80589. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80590. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80591. currentIndex++;
  80592. }
  80593. }
  80594. }
  80595. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80596. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80597. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80598. mesh.setIndices(indices, null);
  80599. if (keepSubMeshes) {
  80600. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80601. var materialIndexOffset = 0, materialMaxIndex;
  80602. mesh.subMeshes = new Array();
  80603. for (var m in subMesh_dict) {
  80604. materialMaxIndex = -1;
  80605. for (var sm in subMesh_dict[m]) {
  80606. subMesh_obj = subMesh_dict[m][sm];
  80607. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80608. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80609. }
  80610. materialIndexOffset += ++materialMaxIndex;
  80611. }
  80612. }
  80613. return mesh;
  80614. };
  80615. // Build Mesh from CSG taking material and transforms into account
  80616. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80617. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80618. mesh.material = material;
  80619. mesh.position.copyFrom(this.position);
  80620. mesh.rotation.copyFrom(this.rotation);
  80621. if (this.rotationQuaternion) {
  80622. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80623. }
  80624. mesh.scaling.copyFrom(this.scaling);
  80625. mesh.computeWorldMatrix(true);
  80626. return mesh;
  80627. };
  80628. return CSG;
  80629. }());
  80630. BABYLON.CSG = CSG;
  80631. })(BABYLON || (BABYLON = {}));
  80632. //# sourceMappingURL=babylon.csg.js.map
  80633. var BABYLON;
  80634. (function (BABYLON) {
  80635. var LensFlare = /** @class */ (function () {
  80636. function LensFlare(size, position, color, imgUrl, system) {
  80637. this.size = size;
  80638. this.position = position;
  80639. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80640. this.color = color || new BABYLON.Color3(1, 1, 1);
  80641. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80642. this._system = system;
  80643. system.lensFlares.push(this);
  80644. }
  80645. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80646. return new LensFlare(size, position, color, imgUrl, system);
  80647. };
  80648. LensFlare.prototype.dispose = function () {
  80649. if (this.texture) {
  80650. this.texture.dispose();
  80651. }
  80652. // Remove from scene
  80653. var index = this._system.lensFlares.indexOf(this);
  80654. this._system.lensFlares.splice(index, 1);
  80655. };
  80656. ;
  80657. return LensFlare;
  80658. }());
  80659. BABYLON.LensFlare = LensFlare;
  80660. })(BABYLON || (BABYLON = {}));
  80661. //# sourceMappingURL=babylon.lensFlare.js.map
  80662. var BABYLON;
  80663. (function (BABYLON) {
  80664. var LensFlareSystem = /** @class */ (function () {
  80665. function LensFlareSystem(name, emitter, scene) {
  80666. this.name = name;
  80667. this.lensFlares = new Array();
  80668. this.borderLimit = 300;
  80669. this.viewportBorder = 0;
  80670. this.layerMask = 0x0FFFFFFF;
  80671. this._vertexBuffers = {};
  80672. this._isEnabled = true;
  80673. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80674. this._emitter = emitter;
  80675. this.id = name;
  80676. scene.lensFlareSystems.push(this);
  80677. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80678. var engine = scene.getEngine();
  80679. // VBO
  80680. var vertices = [];
  80681. vertices.push(1, 1);
  80682. vertices.push(-1, 1);
  80683. vertices.push(-1, -1);
  80684. vertices.push(1, -1);
  80685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80686. // Indices
  80687. var indices = [];
  80688. indices.push(0);
  80689. indices.push(1);
  80690. indices.push(2);
  80691. indices.push(0);
  80692. indices.push(2);
  80693. indices.push(3);
  80694. this._indexBuffer = engine.createIndexBuffer(indices);
  80695. // Effects
  80696. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80697. }
  80698. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80699. get: function () {
  80700. return this._isEnabled;
  80701. },
  80702. set: function (value) {
  80703. this._isEnabled = value;
  80704. },
  80705. enumerable: true,
  80706. configurable: true
  80707. });
  80708. LensFlareSystem.prototype.getScene = function () {
  80709. return this._scene;
  80710. };
  80711. LensFlareSystem.prototype.getEmitter = function () {
  80712. return this._emitter;
  80713. };
  80714. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80715. this._emitter = newEmitter;
  80716. };
  80717. LensFlareSystem.prototype.getEmitterPosition = function () {
  80718. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80719. };
  80720. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80721. var position = this.getEmitterPosition();
  80722. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80723. this._positionX = position.x;
  80724. this._positionY = position.y;
  80725. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80726. if (this.viewportBorder > 0) {
  80727. globalViewport.x -= this.viewportBorder;
  80728. globalViewport.y -= this.viewportBorder;
  80729. globalViewport.width += this.viewportBorder * 2;
  80730. globalViewport.height += this.viewportBorder * 2;
  80731. position.x += this.viewportBorder;
  80732. position.y += this.viewportBorder;
  80733. this._positionX += this.viewportBorder;
  80734. this._positionY += this.viewportBorder;
  80735. }
  80736. if (position.z > 0) {
  80737. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80738. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80739. return true;
  80740. }
  80741. return true;
  80742. }
  80743. return false;
  80744. };
  80745. LensFlareSystem.prototype._isVisible = function () {
  80746. if (!this._isEnabled || !this._scene.activeCamera) {
  80747. return false;
  80748. }
  80749. var emitterPosition = this.getEmitterPosition();
  80750. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80751. var distance = direction.length();
  80752. direction.normalize();
  80753. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80754. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80755. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80756. };
  80757. LensFlareSystem.prototype.render = function () {
  80758. if (!this._effect.isReady() || !this._scene.activeCamera)
  80759. return false;
  80760. var engine = this._scene.getEngine();
  80761. var viewport = this._scene.activeCamera.viewport;
  80762. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80763. // Position
  80764. if (!this.computeEffectivePosition(globalViewport)) {
  80765. return false;
  80766. }
  80767. // Visibility
  80768. if (!this._isVisible()) {
  80769. return false;
  80770. }
  80771. // Intensity
  80772. var awayX;
  80773. var awayY;
  80774. if (this._positionX < this.borderLimit + globalViewport.x) {
  80775. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80776. }
  80777. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80778. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80779. }
  80780. else {
  80781. awayX = 0;
  80782. }
  80783. if (this._positionY < this.borderLimit + globalViewport.y) {
  80784. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80785. }
  80786. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80787. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80788. }
  80789. else {
  80790. awayY = 0;
  80791. }
  80792. var away = (awayX > awayY) ? awayX : awayY;
  80793. away -= this.viewportBorder;
  80794. if (away > this.borderLimit) {
  80795. away = this.borderLimit;
  80796. }
  80797. var intensity = 1.0 - (away / this.borderLimit);
  80798. if (intensity < 0) {
  80799. return false;
  80800. }
  80801. if (intensity > 1.0) {
  80802. intensity = 1.0;
  80803. }
  80804. if (this.viewportBorder > 0) {
  80805. globalViewport.x += this.viewportBorder;
  80806. globalViewport.y += this.viewportBorder;
  80807. globalViewport.width -= this.viewportBorder * 2;
  80808. globalViewport.height -= this.viewportBorder * 2;
  80809. this._positionX -= this.viewportBorder;
  80810. this._positionY -= this.viewportBorder;
  80811. }
  80812. // Position
  80813. var centerX = globalViewport.x + globalViewport.width / 2;
  80814. var centerY = globalViewport.y + globalViewport.height / 2;
  80815. var distX = centerX - this._positionX;
  80816. var distY = centerY - this._positionY;
  80817. // Effects
  80818. engine.enableEffect(this._effect);
  80819. engine.setState(false);
  80820. engine.setDepthBuffer(false);
  80821. // VBOs
  80822. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80823. // Flares
  80824. for (var index = 0; index < this.lensFlares.length; index++) {
  80825. var flare = this.lensFlares[index];
  80826. engine.setAlphaMode(flare.alphaMode);
  80827. var x = centerX - (distX * flare.position);
  80828. var y = centerY - (distY * flare.position);
  80829. var cw = flare.size;
  80830. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80831. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80832. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80833. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80834. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80835. // Texture
  80836. this._effect.setTexture("textureSampler", flare.texture);
  80837. // Color
  80838. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80839. // Draw order
  80840. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80841. }
  80842. engine.setDepthBuffer(true);
  80843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  80844. return true;
  80845. };
  80846. LensFlareSystem.prototype.dispose = function () {
  80847. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80848. if (vertexBuffer) {
  80849. vertexBuffer.dispose();
  80850. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80851. }
  80852. if (this._indexBuffer) {
  80853. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80854. this._indexBuffer = null;
  80855. }
  80856. while (this.lensFlares.length) {
  80857. this.lensFlares[0].dispose();
  80858. }
  80859. // Remove from scene
  80860. var index = this._scene.lensFlareSystems.indexOf(this);
  80861. this._scene.lensFlareSystems.splice(index, 1);
  80862. };
  80863. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  80864. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  80865. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  80866. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  80867. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  80868. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  80869. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  80870. var parsedFlare = parsedLensFlareSystem.flares[index];
  80871. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  80872. }
  80873. return lensFlareSystem;
  80874. };
  80875. LensFlareSystem.prototype.serialize = function () {
  80876. var serializationObject = {};
  80877. serializationObject.id = this.id;
  80878. serializationObject.name = this.name;
  80879. serializationObject.emitterId = this.getEmitter().id;
  80880. serializationObject.borderLimit = this.borderLimit;
  80881. serializationObject.flares = [];
  80882. for (var index = 0; index < this.lensFlares.length; index++) {
  80883. var flare = this.lensFlares[index];
  80884. serializationObject.flares.push({
  80885. size: flare.size,
  80886. position: flare.position,
  80887. color: flare.color.asArray(),
  80888. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  80889. });
  80890. }
  80891. return serializationObject;
  80892. };
  80893. return LensFlareSystem;
  80894. }());
  80895. BABYLON.LensFlareSystem = LensFlareSystem;
  80896. })(BABYLON || (BABYLON = {}));
  80897. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  80898. var BABYLON;
  80899. (function (BABYLON) {
  80900. /**
  80901. * This is a holder class for the physics joint created by the physics plugin.
  80902. * It holds a set of functions to control the underlying joint.
  80903. */
  80904. var PhysicsJoint = /** @class */ (function () {
  80905. function PhysicsJoint(type, jointData) {
  80906. this.type = type;
  80907. this.jointData = jointData;
  80908. jointData.nativeParams = jointData.nativeParams || {};
  80909. }
  80910. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  80911. get: function () {
  80912. return this._physicsJoint;
  80913. },
  80914. set: function (newJoint) {
  80915. if (this._physicsJoint) {
  80916. //remove from the wolrd
  80917. }
  80918. this._physicsJoint = newJoint;
  80919. },
  80920. enumerable: true,
  80921. configurable: true
  80922. });
  80923. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  80924. set: function (physicsPlugin) {
  80925. this._physicsPlugin = physicsPlugin;
  80926. },
  80927. enumerable: true,
  80928. configurable: true
  80929. });
  80930. /**
  80931. * Execute a function that is physics-plugin specific.
  80932. * @param {Function} func the function that will be executed.
  80933. * It accepts two parameters: the physics world and the physics joint.
  80934. */
  80935. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  80936. func(this._physicsPlugin.world, this._physicsJoint);
  80937. };
  80938. //TODO check if the native joints are the same
  80939. //Joint Types
  80940. PhysicsJoint.DistanceJoint = 0;
  80941. PhysicsJoint.HingeJoint = 1;
  80942. PhysicsJoint.BallAndSocketJoint = 2;
  80943. PhysicsJoint.WheelJoint = 3;
  80944. PhysicsJoint.SliderJoint = 4;
  80945. //OIMO
  80946. PhysicsJoint.PrismaticJoint = 5;
  80947. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  80948. PhysicsJoint.UniversalJoint = 6;
  80949. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  80950. //Cannon
  80951. //Similar to a Ball-Joint. Different in params
  80952. PhysicsJoint.PointToPointJoint = 8;
  80953. //Cannon only at the moment
  80954. PhysicsJoint.SpringJoint = 9;
  80955. PhysicsJoint.LockJoint = 10;
  80956. return PhysicsJoint;
  80957. }());
  80958. BABYLON.PhysicsJoint = PhysicsJoint;
  80959. /**
  80960. * A class representing a physics distance joint.
  80961. */
  80962. var DistanceJoint = /** @class */ (function (_super) {
  80963. __extends(DistanceJoint, _super);
  80964. function DistanceJoint(jointData) {
  80965. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  80966. }
  80967. /**
  80968. * Update the predefined distance.
  80969. */
  80970. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  80971. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  80972. };
  80973. return DistanceJoint;
  80974. }(PhysicsJoint));
  80975. BABYLON.DistanceJoint = DistanceJoint;
  80976. var MotorEnabledJoint = /** @class */ (function (_super) {
  80977. __extends(MotorEnabledJoint, _super);
  80978. function MotorEnabledJoint(type, jointData) {
  80979. return _super.call(this, type, jointData) || this;
  80980. }
  80981. /**
  80982. * Set the motor values.
  80983. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80984. * @param {number} force the force to apply
  80985. * @param {number} maxForce max force for this motor.
  80986. */
  80987. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  80988. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  80989. };
  80990. /**
  80991. * Set the motor's limits.
  80992. * Attention, this function is plugin specific. Engines won't react 100% the same.
  80993. */
  80994. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  80995. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  80996. };
  80997. return MotorEnabledJoint;
  80998. }(PhysicsJoint));
  80999. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81000. /**
  81001. * This class represents a single hinge physics joint
  81002. */
  81003. var HingeJoint = /** @class */ (function (_super) {
  81004. __extends(HingeJoint, _super);
  81005. function HingeJoint(jointData) {
  81006. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81007. }
  81008. /**
  81009. * Set the motor values.
  81010. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81011. * @param {number} force the force to apply
  81012. * @param {number} maxForce max force for this motor.
  81013. */
  81014. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81015. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81016. };
  81017. /**
  81018. * Set the motor's limits.
  81019. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81020. */
  81021. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81022. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81023. };
  81024. return HingeJoint;
  81025. }(MotorEnabledJoint));
  81026. BABYLON.HingeJoint = HingeJoint;
  81027. /**
  81028. * This class represents a dual hinge physics joint (same as wheel joint)
  81029. */
  81030. var Hinge2Joint = /** @class */ (function (_super) {
  81031. __extends(Hinge2Joint, _super);
  81032. function Hinge2Joint(jointData) {
  81033. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81034. }
  81035. /**
  81036. * Set the motor values.
  81037. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81038. * @param {number} force the force to apply
  81039. * @param {number} maxForce max force for this motor.
  81040. * @param {motorIndex} the motor's index, 0 or 1.
  81041. */
  81042. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81043. if (motorIndex === void 0) { motorIndex = 0; }
  81044. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81045. };
  81046. /**
  81047. * Set the motor limits.
  81048. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81049. * @param {number} upperLimit the upper limit
  81050. * @param {number} lowerLimit lower limit
  81051. * @param {motorIndex} the motor's index, 0 or 1.
  81052. */
  81053. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81054. if (motorIndex === void 0) { motorIndex = 0; }
  81055. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81056. };
  81057. return Hinge2Joint;
  81058. }(MotorEnabledJoint));
  81059. BABYLON.Hinge2Joint = Hinge2Joint;
  81060. })(BABYLON || (BABYLON = {}));
  81061. //# sourceMappingURL=babylon.physicsJoint.js.map
  81062. var BABYLON;
  81063. (function (BABYLON) {
  81064. var PhysicsImpostor = /** @class */ (function () {
  81065. function PhysicsImpostor(object, type, _options, _scene) {
  81066. if (_options === void 0) { _options = { mass: 0 }; }
  81067. var _this = this;
  81068. this.object = object;
  81069. this.type = type;
  81070. this._options = _options;
  81071. this._scene = _scene;
  81072. this._bodyUpdateRequired = false;
  81073. this._onBeforePhysicsStepCallbacks = new Array();
  81074. this._onAfterPhysicsStepCallbacks = new Array();
  81075. this._onPhysicsCollideCallbacks = [];
  81076. this._deltaPosition = BABYLON.Vector3.Zero();
  81077. this._isDisposed = false;
  81078. //temp variables for parent rotation calculations
  81079. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81080. this._tmpQuat = new BABYLON.Quaternion();
  81081. this._tmpQuat2 = new BABYLON.Quaternion();
  81082. /**
  81083. * this function is executed by the physics engine.
  81084. */
  81085. this.beforeStep = function () {
  81086. if (!_this._physicsEngine) {
  81087. return;
  81088. }
  81089. _this.object.translate(_this._deltaPosition, -1);
  81090. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81091. _this.object.computeWorldMatrix(false);
  81092. if (_this.object.parent && _this.object.rotationQuaternion) {
  81093. _this.getParentsRotation();
  81094. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81095. }
  81096. else {
  81097. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81098. }
  81099. if (!_this._options.disableBidirectionalTransformation) {
  81100. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81101. }
  81102. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81103. func(_this);
  81104. });
  81105. };
  81106. /**
  81107. * this function is executed by the physics engine.
  81108. */
  81109. this.afterStep = function () {
  81110. if (!_this._physicsEngine) {
  81111. return;
  81112. }
  81113. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81114. func(_this);
  81115. });
  81116. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81117. // object has now its world rotation. needs to be converted to local.
  81118. if (_this.object.parent && _this.object.rotationQuaternion) {
  81119. _this.getParentsRotation();
  81120. _this._tmpQuat.conjugateInPlace();
  81121. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81122. }
  81123. // take the position set and make it the absolute position of this object.
  81124. _this.object.setAbsolutePosition(_this.object.position);
  81125. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81126. _this.object.translate(_this._deltaPosition, 1);
  81127. };
  81128. /**
  81129. * Legacy collision detection event support
  81130. */
  81131. this.onCollideEvent = null;
  81132. //event and body object due to cannon's event-based architecture.
  81133. this.onCollide = function (e) {
  81134. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81135. return;
  81136. }
  81137. if (!_this._physicsEngine) {
  81138. return;
  81139. }
  81140. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81141. if (otherImpostor) {
  81142. // Legacy collision detection event support
  81143. if (_this.onCollideEvent) {
  81144. _this.onCollideEvent(_this, otherImpostor);
  81145. }
  81146. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81147. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81148. }).forEach(function (obj) {
  81149. obj.callback(_this, otherImpostor);
  81150. });
  81151. }
  81152. };
  81153. //sanity check!
  81154. if (!this.object) {
  81155. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81156. return;
  81157. }
  81158. //legacy support for old syntax.
  81159. if (!this._scene && object.getScene) {
  81160. this._scene = object.getScene();
  81161. }
  81162. if (!this._scene) {
  81163. return;
  81164. }
  81165. this._physicsEngine = this._scene.getPhysicsEngine();
  81166. if (!this._physicsEngine) {
  81167. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81168. }
  81169. else {
  81170. //set the object's quaternion, if not set
  81171. if (!this.object.rotationQuaternion) {
  81172. if (this.object.rotation) {
  81173. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81174. }
  81175. else {
  81176. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81177. }
  81178. }
  81179. //default options params
  81180. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81181. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81182. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81183. this._joints = [];
  81184. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81185. if (!this.object.parent || this._options.ignoreParent) {
  81186. this._init();
  81187. }
  81188. else if (this.object.parent.physicsImpostor) {
  81189. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81190. }
  81191. }
  81192. }
  81193. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81194. get: function () {
  81195. return this._isDisposed;
  81196. },
  81197. enumerable: true,
  81198. configurable: true
  81199. });
  81200. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81201. get: function () {
  81202. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81203. },
  81204. set: function (value) {
  81205. this.setMass(value);
  81206. },
  81207. enumerable: true,
  81208. configurable: true
  81209. });
  81210. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81211. get: function () {
  81212. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81213. },
  81214. set: function (value) {
  81215. if (!this._physicsEngine) {
  81216. return;
  81217. }
  81218. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81219. },
  81220. enumerable: true,
  81221. configurable: true
  81222. });
  81223. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81224. get: function () {
  81225. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81226. },
  81227. set: function (value) {
  81228. if (!this._physicsEngine) {
  81229. return;
  81230. }
  81231. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81232. },
  81233. enumerable: true,
  81234. configurable: true
  81235. });
  81236. /**
  81237. * This function will completly initialize this impostor.
  81238. * It will create a new body - but only if this mesh has no parent.
  81239. * If it has, this impostor will not be used other than to define the impostor
  81240. * of the child mesh.
  81241. */
  81242. PhysicsImpostor.prototype._init = function () {
  81243. if (!this._physicsEngine) {
  81244. return;
  81245. }
  81246. this._physicsEngine.removeImpostor(this);
  81247. this.physicsBody = null;
  81248. this._parent = this._parent || this._getPhysicsParent();
  81249. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81250. this._physicsEngine.addImpostor(this);
  81251. }
  81252. };
  81253. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81254. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81255. var parentMesh = this.object.parent;
  81256. return parentMesh.physicsImpostor;
  81257. }
  81258. return null;
  81259. };
  81260. /**
  81261. * Should a new body be generated.
  81262. */
  81263. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81264. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81265. };
  81266. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81267. this.forceUpdate();
  81268. };
  81269. /**
  81270. * Force a regeneration of this or the parent's impostor's body.
  81271. * Use under cautious - This will remove all joints already implemented.
  81272. */
  81273. PhysicsImpostor.prototype.forceUpdate = function () {
  81274. this._init();
  81275. if (this.parent && !this._options.ignoreParent) {
  81276. this.parent.forceUpdate();
  81277. }
  81278. };
  81279. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81280. /*public get mesh(): AbstractMesh {
  81281. return this._mesh;
  81282. }*/
  81283. /**
  81284. * Gets the body that holds this impostor. Either its own, or its parent.
  81285. */
  81286. get: function () {
  81287. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81288. },
  81289. /**
  81290. * Set the physics body. Used mainly by the physics engine/plugin
  81291. */
  81292. set: function (physicsBody) {
  81293. if (this._physicsBody && this._physicsEngine) {
  81294. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81295. }
  81296. this._physicsBody = physicsBody;
  81297. this.resetUpdateFlags();
  81298. },
  81299. enumerable: true,
  81300. configurable: true
  81301. });
  81302. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81303. get: function () {
  81304. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81305. },
  81306. set: function (value) {
  81307. this._parent = value;
  81308. },
  81309. enumerable: true,
  81310. configurable: true
  81311. });
  81312. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81313. this._bodyUpdateRequired = false;
  81314. };
  81315. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81316. if (this.object.getBoundingInfo) {
  81317. var q = this.object.rotationQuaternion;
  81318. //reset rotation
  81319. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81320. //calculate the world matrix with no rotation
  81321. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81322. var boundingInfo = this.object.getBoundingInfo();
  81323. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81324. //bring back the rotation
  81325. this.object.rotationQuaternion = q;
  81326. //calculate the world matrix with the new rotation
  81327. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81328. return size;
  81329. }
  81330. else {
  81331. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81332. }
  81333. };
  81334. PhysicsImpostor.prototype.getObjectCenter = function () {
  81335. if (this.object.getBoundingInfo) {
  81336. var boundingInfo = this.object.getBoundingInfo();
  81337. return boundingInfo.boundingBox.centerWorld;
  81338. }
  81339. else {
  81340. return this.object.position;
  81341. }
  81342. };
  81343. /**
  81344. * Get a specific parametes from the options parameter.
  81345. */
  81346. PhysicsImpostor.prototype.getParam = function (paramName) {
  81347. return this._options[paramName];
  81348. };
  81349. /**
  81350. * Sets a specific parameter in the options given to the physics plugin
  81351. */
  81352. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81353. this._options[paramName] = value;
  81354. this._bodyUpdateRequired = true;
  81355. };
  81356. /**
  81357. * Specifically change the body's mass option. Won't recreate the physics body object
  81358. */
  81359. PhysicsImpostor.prototype.setMass = function (mass) {
  81360. if (this.getParam("mass") !== mass) {
  81361. this.setParam("mass", mass);
  81362. }
  81363. if (this._physicsEngine) {
  81364. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81365. }
  81366. };
  81367. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81368. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81369. };
  81370. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81371. if (this._physicsEngine) {
  81372. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81373. }
  81374. };
  81375. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81376. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81377. };
  81378. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81379. if (this._physicsEngine) {
  81380. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81381. }
  81382. };
  81383. /**
  81384. * Execute a function with the physics plugin native code.
  81385. * Provide a function the will have two variables - the world object and the physics body object.
  81386. */
  81387. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81388. if (this._physicsEngine) {
  81389. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81390. }
  81391. };
  81392. /**
  81393. * Register a function that will be executed before the physics world is stepping forward.
  81394. */
  81395. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81396. this._onBeforePhysicsStepCallbacks.push(func);
  81397. };
  81398. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81399. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81400. if (index > -1) {
  81401. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81402. }
  81403. else {
  81404. BABYLON.Tools.Warn("Function to remove was not found");
  81405. }
  81406. };
  81407. /**
  81408. * Register a function that will be executed after the physics step
  81409. */
  81410. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81411. this._onAfterPhysicsStepCallbacks.push(func);
  81412. };
  81413. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81414. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81415. if (index > -1) {
  81416. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81417. }
  81418. else {
  81419. BABYLON.Tools.Warn("Function to remove was not found");
  81420. }
  81421. };
  81422. /**
  81423. * register a function that will be executed when this impostor collides against a different body.
  81424. */
  81425. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81426. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81427. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81428. };
  81429. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81430. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81431. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81432. if (index > -1) {
  81433. this._onPhysicsCollideCallbacks.splice(index, 1);
  81434. }
  81435. else {
  81436. BABYLON.Tools.Warn("Function to remove was not found");
  81437. }
  81438. };
  81439. PhysicsImpostor.prototype.getParentsRotation = function () {
  81440. var parent = this.object.parent;
  81441. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81442. while (parent) {
  81443. if (parent.rotationQuaternion) {
  81444. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81445. }
  81446. else {
  81447. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81448. }
  81449. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81450. parent = parent.parent;
  81451. }
  81452. return this._tmpQuat;
  81453. };
  81454. /**
  81455. * Apply a force
  81456. */
  81457. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81458. if (this._physicsEngine) {
  81459. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81460. }
  81461. return this;
  81462. };
  81463. /**
  81464. * Apply an impulse
  81465. */
  81466. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81467. if (this._physicsEngine) {
  81468. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81469. }
  81470. return this;
  81471. };
  81472. /**
  81473. * A help function to create a joint.
  81474. */
  81475. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81476. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81477. this.addJoint(otherImpostor, joint);
  81478. return this;
  81479. };
  81480. /**
  81481. * Add a joint to this impostor with a different impostor.
  81482. */
  81483. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81484. this._joints.push({
  81485. otherImpostor: otherImpostor,
  81486. joint: joint
  81487. });
  81488. if (this._physicsEngine) {
  81489. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81490. }
  81491. return this;
  81492. };
  81493. /**
  81494. * Will keep this body still, in a sleep mode.
  81495. */
  81496. PhysicsImpostor.prototype.sleep = function () {
  81497. if (this._physicsEngine) {
  81498. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81499. }
  81500. return this;
  81501. };
  81502. /**
  81503. * Wake the body up.
  81504. */
  81505. PhysicsImpostor.prototype.wakeUp = function () {
  81506. if (this._physicsEngine) {
  81507. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81508. }
  81509. return this;
  81510. };
  81511. PhysicsImpostor.prototype.clone = function (newObject) {
  81512. if (!newObject)
  81513. return null;
  81514. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81515. };
  81516. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81517. var _this = this;
  81518. //no dispose if no physics engine is available.
  81519. if (!this._physicsEngine) {
  81520. return;
  81521. }
  81522. this._joints.forEach(function (j) {
  81523. if (_this._physicsEngine) {
  81524. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81525. }
  81526. });
  81527. //dispose the physics body
  81528. this._physicsEngine.removeImpostor(this);
  81529. if (this.parent) {
  81530. this.parent.forceUpdate();
  81531. }
  81532. else {
  81533. /*this._object.getChildMeshes().forEach(function(mesh) {
  81534. if (mesh.physicsImpostor) {
  81535. if (disposeChildren) {
  81536. mesh.physicsImpostor.dispose();
  81537. mesh.physicsImpostor = null;
  81538. }
  81539. }
  81540. })*/
  81541. }
  81542. this._isDisposed = true;
  81543. };
  81544. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81545. this._deltaPosition.copyFrom(position);
  81546. };
  81547. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  81548. if (!this._deltaRotation) {
  81549. this._deltaRotation = new BABYLON.Quaternion();
  81550. }
  81551. this._deltaRotation.copyFrom(rotation);
  81552. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  81553. };
  81554. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  81555. if (this._physicsEngine) {
  81556. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  81557. }
  81558. return this;
  81559. };
  81560. PhysicsImpostor.prototype.getRadius = function () {
  81561. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  81562. };
  81563. /**
  81564. * Sync a bone with this impostor
  81565. * @param bone The bone to sync to the impostor.
  81566. * @param boneMesh The mesh that the bone is influencing.
  81567. * @param jointPivot The pivot of the joint / bone in local space.
  81568. * @param distToJoint Optional distance from the impostor to the joint.
  81569. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81570. */
  81571. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  81572. var tempVec = PhysicsImpostor._tmpVecs[0];
  81573. var mesh = this.object;
  81574. if (mesh.rotationQuaternion) {
  81575. if (adjustRotation) {
  81576. var tempQuat = PhysicsImpostor._tmpQuat;
  81577. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81578. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81579. }
  81580. else {
  81581. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81582. }
  81583. }
  81584. tempVec.x = 0;
  81585. tempVec.y = 0;
  81586. tempVec.z = 0;
  81587. if (jointPivot) {
  81588. tempVec.x = jointPivot.x;
  81589. tempVec.y = jointPivot.y;
  81590. tempVec.z = jointPivot.z;
  81591. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81592. if (distToJoint === undefined || distToJoint === null) {
  81593. distToJoint = jointPivot.length();
  81594. }
  81595. tempVec.x *= distToJoint;
  81596. tempVec.y *= distToJoint;
  81597. tempVec.z *= distToJoint;
  81598. }
  81599. if (bone.getParent()) {
  81600. tempVec.addInPlace(mesh.getAbsolutePosition());
  81601. bone.setAbsolutePosition(tempVec, boneMesh);
  81602. }
  81603. else {
  81604. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81605. boneMesh.position.x -= tempVec.x;
  81606. boneMesh.position.y -= tempVec.y;
  81607. boneMesh.position.z -= tempVec.z;
  81608. }
  81609. };
  81610. /**
  81611. * Sync impostor to a bone
  81612. * @param bone The bone that the impostor will be synced to.
  81613. * @param boneMesh The mesh that the bone is influencing.
  81614. * @param jointPivot The pivot of the joint / bone in local space.
  81615. * @param distToJoint Optional distance from the impostor to the joint.
  81616. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81617. * @param boneAxis Optional vector3 axis the bone is aligned with
  81618. */
  81619. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81620. var mesh = this.object;
  81621. if (mesh.rotationQuaternion) {
  81622. if (adjustRotation) {
  81623. var tempQuat = PhysicsImpostor._tmpQuat;
  81624. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81625. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81626. }
  81627. else {
  81628. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81629. }
  81630. }
  81631. var pos = PhysicsImpostor._tmpVecs[0];
  81632. var boneDir = PhysicsImpostor._tmpVecs[1];
  81633. if (!boneAxis) {
  81634. boneAxis = PhysicsImpostor._tmpVecs[2];
  81635. boneAxis.x = 0;
  81636. boneAxis.y = 1;
  81637. boneAxis.z = 0;
  81638. }
  81639. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81640. bone.getAbsolutePositionToRef(boneMesh, pos);
  81641. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81642. distToJoint = jointPivot.length();
  81643. }
  81644. if (distToJoint !== undefined && distToJoint !== null) {
  81645. pos.x += boneDir.x * distToJoint;
  81646. pos.y += boneDir.y * distToJoint;
  81647. pos.z += boneDir.z * distToJoint;
  81648. }
  81649. mesh.setAbsolutePosition(pos);
  81650. };
  81651. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81652. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81653. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81654. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81655. //Impostor types
  81656. PhysicsImpostor.NoImpostor = 0;
  81657. PhysicsImpostor.SphereImpostor = 1;
  81658. PhysicsImpostor.BoxImpostor = 2;
  81659. PhysicsImpostor.PlaneImpostor = 3;
  81660. PhysicsImpostor.MeshImpostor = 4;
  81661. PhysicsImpostor.CylinderImpostor = 7;
  81662. PhysicsImpostor.ParticleImpostor = 8;
  81663. PhysicsImpostor.HeightmapImpostor = 9;
  81664. return PhysicsImpostor;
  81665. }());
  81666. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81667. })(BABYLON || (BABYLON = {}));
  81668. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81669. var BABYLON;
  81670. (function (BABYLON) {
  81671. var PhysicsEngine = /** @class */ (function () {
  81672. function PhysicsEngine(gravity, _physicsPlugin) {
  81673. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81674. this._physicsPlugin = _physicsPlugin;
  81675. //new methods and parameters
  81676. this._impostors = [];
  81677. this._joints = [];
  81678. if (!this._physicsPlugin.isSupported()) {
  81679. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81680. + "Please make sure it is included.");
  81681. }
  81682. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81683. this.setGravity(gravity);
  81684. this.setTimeStep();
  81685. }
  81686. PhysicsEngine.prototype.setGravity = function (gravity) {
  81687. this.gravity = gravity;
  81688. this._physicsPlugin.setGravity(this.gravity);
  81689. };
  81690. /**
  81691. * Set the time step of the physics engine.
  81692. * default is 1/60.
  81693. * To slow it down, enter 1/600 for example.
  81694. * To speed it up, 1/30
  81695. * @param {number} newTimeStep the new timestep to apply to this world.
  81696. */
  81697. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81698. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81699. this._physicsPlugin.setTimeStep(newTimeStep);
  81700. };
  81701. /**
  81702. * Get the time step of the physics engine.
  81703. */
  81704. PhysicsEngine.prototype.getTimeStep = function () {
  81705. return this._physicsPlugin.getTimeStep();
  81706. };
  81707. PhysicsEngine.prototype.dispose = function () {
  81708. this._impostors.forEach(function (impostor) {
  81709. impostor.dispose();
  81710. });
  81711. this._physicsPlugin.dispose();
  81712. };
  81713. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81714. return this._physicsPlugin.name;
  81715. };
  81716. /**
  81717. * Adding a new impostor for the impostor tracking.
  81718. * This will be done by the impostor itself.
  81719. * @param {PhysicsImpostor} impostor the impostor to add
  81720. */
  81721. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81722. impostor.uniqueId = this._impostors.push(impostor);
  81723. //if no parent, generate the body
  81724. if (!impostor.parent) {
  81725. this._physicsPlugin.generatePhysicsBody(impostor);
  81726. }
  81727. };
  81728. /**
  81729. * Remove an impostor from the engine.
  81730. * This impostor and its mesh will not longer be updated by the physics engine.
  81731. * @param {PhysicsImpostor} impostor the impostor to remove
  81732. */
  81733. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81734. var index = this._impostors.indexOf(impostor);
  81735. if (index > -1) {
  81736. var removed = this._impostors.splice(index, 1);
  81737. //Is it needed?
  81738. if (removed.length) {
  81739. //this will also remove it from the world.
  81740. removed[0].physicsBody = null;
  81741. }
  81742. }
  81743. };
  81744. /**
  81745. * Add a joint to the physics engine
  81746. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81747. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81748. * @param {PhysicsJoint} the joint that will connect both impostors.
  81749. */
  81750. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81751. var impostorJoint = {
  81752. mainImpostor: mainImpostor,
  81753. connectedImpostor: connectedImpostor,
  81754. joint: joint
  81755. };
  81756. joint.physicsPlugin = this._physicsPlugin;
  81757. this._joints.push(impostorJoint);
  81758. this._physicsPlugin.generateJoint(impostorJoint);
  81759. };
  81760. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81761. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81762. return (impostorJoint.connectedImpostor === connectedImpostor
  81763. && impostorJoint.joint === joint
  81764. && impostorJoint.mainImpostor === mainImpostor);
  81765. });
  81766. if (matchingJoints.length) {
  81767. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81768. //TODO remove it from the list as well
  81769. }
  81770. };
  81771. /**
  81772. * Called by the scene. no need to call it.
  81773. */
  81774. PhysicsEngine.prototype._step = function (delta) {
  81775. var _this = this;
  81776. //check if any mesh has no body / requires an update
  81777. this._impostors.forEach(function (impostor) {
  81778. if (impostor.isBodyInitRequired()) {
  81779. _this._physicsPlugin.generatePhysicsBody(impostor);
  81780. }
  81781. });
  81782. if (delta > 0.1) {
  81783. delta = 0.1;
  81784. }
  81785. else if (delta <= 0) {
  81786. delta = 1.0 / 60.0;
  81787. }
  81788. this._physicsPlugin.executeStep(delta, this._impostors);
  81789. };
  81790. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81791. return this._physicsPlugin;
  81792. };
  81793. PhysicsEngine.prototype.getImpostors = function () {
  81794. return this._impostors;
  81795. };
  81796. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81797. for (var i = 0; i < this._impostors.length; ++i) {
  81798. if (this._impostors[i].object === object) {
  81799. return this._impostors[i];
  81800. }
  81801. }
  81802. return null;
  81803. };
  81804. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81805. for (var i = 0; i < this._impostors.length; ++i) {
  81806. if (this._impostors[i].physicsBody === body) {
  81807. return this._impostors[i];
  81808. }
  81809. }
  81810. return null;
  81811. };
  81812. // Statics
  81813. PhysicsEngine.Epsilon = 0.001;
  81814. return PhysicsEngine;
  81815. }());
  81816. BABYLON.PhysicsEngine = PhysicsEngine;
  81817. })(BABYLON || (BABYLON = {}));
  81818. //# sourceMappingURL=babylon.physicsEngine.js.map
  81819. var BABYLON;
  81820. (function (BABYLON) {
  81821. var PhysicsHelper = /** @class */ (function () {
  81822. function PhysicsHelper(scene) {
  81823. this._scene = scene;
  81824. this._physicsEngine = this._scene.getPhysicsEngine();
  81825. if (!this._physicsEngine) {
  81826. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81827. }
  81828. }
  81829. /**
  81830. * @param {Vector3} origin the origin of the explosion
  81831. * @param {number} radius the explosion radius
  81832. * @param {number} strength the explosion strength
  81833. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81834. */
  81835. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81836. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81837. if (!this._physicsEngine) {
  81838. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81839. return null;
  81840. }
  81841. var impostors = this._physicsEngine.getImpostors();
  81842. if (impostors.length === 0) {
  81843. return null;
  81844. }
  81845. var event = new PhysicsRadialExplosionEvent(this._scene);
  81846. impostors.forEach(function (impostor) {
  81847. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81848. if (!impostorForceAndContactPoint) {
  81849. return;
  81850. }
  81851. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81852. });
  81853. event.dispose(false);
  81854. return event;
  81855. };
  81856. /**
  81857. * @param {Vector3} origin the origin of the explosion
  81858. * @param {number} radius the explosion radius
  81859. * @param {number} strength the explosion strength
  81860. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81861. */
  81862. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  81863. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81864. if (!this._physicsEngine) {
  81865. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81866. return null;
  81867. }
  81868. var impostors = this._physicsEngine.getImpostors();
  81869. if (impostors.length === 0) {
  81870. return null;
  81871. }
  81872. var event = new PhysicsRadialExplosionEvent(this._scene);
  81873. impostors.forEach(function (impostor) {
  81874. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  81875. if (!impostorForceAndContactPoint) {
  81876. return;
  81877. }
  81878. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  81879. });
  81880. event.dispose(false);
  81881. return event;
  81882. };
  81883. /**
  81884. * @param {Vector3} origin the origin of the explosion
  81885. * @param {number} radius the explosion radius
  81886. * @param {number} strength the explosion strength
  81887. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81888. */
  81889. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  81890. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81891. if (!this._physicsEngine) {
  81892. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81893. return null;
  81894. }
  81895. var impostors = this._physicsEngine.getImpostors();
  81896. if (impostors.length === 0) {
  81897. return null;
  81898. }
  81899. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  81900. event.dispose(false);
  81901. return event;
  81902. };
  81903. /**
  81904. * @param {Vector3} origin the origin of the updraft
  81905. * @param {number} radius the radius of the updraft
  81906. * @param {number} strength the strength of the updraft
  81907. * @param {number} height the height of the updraft
  81908. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  81909. */
  81910. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  81911. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  81912. if (!this._physicsEngine) {
  81913. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81914. return null;
  81915. }
  81916. if (this._physicsEngine.getImpostors().length === 0) {
  81917. return null;
  81918. }
  81919. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  81920. event.dispose(false);
  81921. return event;
  81922. };
  81923. /**
  81924. * @param {Vector3} origin the of the vortex
  81925. * @param {number} radius the radius of the vortex
  81926. * @param {number} strength the strength of the vortex
  81927. * @param {number} height the height of the vortex
  81928. */
  81929. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  81930. if (!this._physicsEngine) {
  81931. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  81932. return null;
  81933. }
  81934. if (this._physicsEngine.getImpostors().length === 0) {
  81935. return null;
  81936. }
  81937. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  81938. event.dispose(false);
  81939. return event;
  81940. };
  81941. return PhysicsHelper;
  81942. }());
  81943. BABYLON.PhysicsHelper = PhysicsHelper;
  81944. /***** Radial explosion *****/
  81945. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  81946. function PhysicsRadialExplosionEvent(scene) {
  81947. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  81948. this._rays = [];
  81949. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  81950. this._scene = scene;
  81951. }
  81952. /**
  81953. * Returns the data related to the radial explosion event (sphere & rays).
  81954. * @returns {PhysicsRadialExplosionEventData}
  81955. */
  81956. PhysicsRadialExplosionEvent.prototype.getData = function () {
  81957. this._dataFetched = true;
  81958. return {
  81959. sphere: this._sphere,
  81960. rays: this._rays,
  81961. };
  81962. };
  81963. /**
  81964. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  81965. * @param impostor
  81966. * @param {Vector3} origin the origin of the explosion
  81967. * @param {number} radius the explosion radius
  81968. * @param {number} strength the explosion strength
  81969. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  81970. * @returns {Nullable<PhysicsForceAndContactPoint>}
  81971. */
  81972. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  81973. if (impostor.mass === 0) {
  81974. return null;
  81975. }
  81976. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  81977. return null;
  81978. }
  81979. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  81980. return null;
  81981. }
  81982. var impostorObjectCenter = impostor.getObjectCenter();
  81983. var direction = impostorObjectCenter.subtract(origin);
  81984. var ray = new BABYLON.Ray(origin, direction, radius);
  81985. this._rays.push(ray);
  81986. var hit = ray.intersectsMesh(impostor.object);
  81987. var contactPoint = hit.pickedPoint;
  81988. if (!contactPoint) {
  81989. return null;
  81990. }
  81991. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  81992. if (distanceFromOrigin > radius) {
  81993. return null;
  81994. }
  81995. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  81996. ? strength
  81997. : strength * (1 - (distanceFromOrigin / radius));
  81998. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  81999. return { force: force, contactPoint: contactPoint };
  82000. };
  82001. /**
  82002. * Disposes the sphere.
  82003. * @param {bolean} force
  82004. */
  82005. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82006. var _this = this;
  82007. if (force === void 0) { force = true; }
  82008. if (force) {
  82009. this._sphere.dispose();
  82010. }
  82011. else {
  82012. setTimeout(function () {
  82013. if (!_this._dataFetched) {
  82014. _this._sphere.dispose();
  82015. }
  82016. }, 0);
  82017. }
  82018. };
  82019. /*** Helpers ***/
  82020. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82021. if (!this._sphere) {
  82022. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82023. this._sphere.isVisible = false;
  82024. }
  82025. };
  82026. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82027. var impostorObject = impostor.object;
  82028. this._prepareSphere();
  82029. this._sphere.position = origin;
  82030. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82031. this._sphere._updateBoundingInfo();
  82032. this._sphere.computeWorldMatrix(true);
  82033. return this._sphere.intersectsMesh(impostorObject, true);
  82034. };
  82035. return PhysicsRadialExplosionEvent;
  82036. }());
  82037. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82038. /***** Gravitational Field *****/
  82039. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82040. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82041. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82042. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82043. this._physicsHelper = physicsHelper;
  82044. this._scene = scene;
  82045. this._origin = origin;
  82046. this._radius = radius;
  82047. this._strength = strength;
  82048. this._falloff = falloff;
  82049. this._tickCallback = this._tick.bind(this);
  82050. }
  82051. /**
  82052. * Returns the data related to the gravitational field event (sphere).
  82053. * @returns {PhysicsGravitationalFieldEventData}
  82054. */
  82055. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82056. this._dataFetched = true;
  82057. return {
  82058. sphere: this._sphere,
  82059. };
  82060. };
  82061. /**
  82062. * Enables the gravitational field.
  82063. */
  82064. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82065. this._tickCallback.call(this);
  82066. this._scene.registerBeforeRender(this._tickCallback);
  82067. };
  82068. /**
  82069. * Disables the gravitational field.
  82070. */
  82071. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82072. this._scene.unregisterBeforeRender(this._tickCallback);
  82073. };
  82074. /**
  82075. * Disposes the sphere.
  82076. * @param {bolean} force
  82077. */
  82078. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82079. var _this = this;
  82080. if (force === void 0) { force = true; }
  82081. if (force) {
  82082. this._sphere.dispose();
  82083. }
  82084. else {
  82085. setTimeout(function () {
  82086. if (!_this._dataFetched) {
  82087. _this._sphere.dispose();
  82088. }
  82089. }, 0);
  82090. }
  82091. };
  82092. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82093. // Since the params won't change, we fetch the event only once
  82094. if (this._sphere) {
  82095. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82096. }
  82097. else {
  82098. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82099. if (radialExplosionEvent) {
  82100. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82101. }
  82102. }
  82103. };
  82104. return PhysicsGravitationalFieldEvent;
  82105. }());
  82106. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82107. /***** Updraft *****/
  82108. var PhysicsUpdraftEvent = /** @class */ (function () {
  82109. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82110. this._scene = _scene;
  82111. this._origin = _origin;
  82112. this._radius = _radius;
  82113. this._strength = _strength;
  82114. this._height = _height;
  82115. this._updraftMode = _updraftMode;
  82116. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82117. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82118. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82119. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82120. this._physicsEngine = this._scene.getPhysicsEngine();
  82121. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82122. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82123. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82124. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82125. }
  82126. this._tickCallback = this._tick.bind(this);
  82127. }
  82128. /**
  82129. * Returns the data related to the updraft event (cylinder).
  82130. * @returns {PhysicsUpdraftEventData}
  82131. */
  82132. PhysicsUpdraftEvent.prototype.getData = function () {
  82133. this._dataFetched = true;
  82134. return {
  82135. cylinder: this._cylinder,
  82136. };
  82137. };
  82138. /**
  82139. * Enables the updraft.
  82140. */
  82141. PhysicsUpdraftEvent.prototype.enable = function () {
  82142. this._tickCallback.call(this);
  82143. this._scene.registerBeforeRender(this._tickCallback);
  82144. };
  82145. /**
  82146. * Disables the cortex.
  82147. */
  82148. PhysicsUpdraftEvent.prototype.disable = function () {
  82149. this._scene.unregisterBeforeRender(this._tickCallback);
  82150. };
  82151. /**
  82152. * Disposes the sphere.
  82153. * @param {bolean} force
  82154. */
  82155. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82156. var _this = this;
  82157. if (force === void 0) { force = true; }
  82158. if (force) {
  82159. this._cylinder.dispose();
  82160. }
  82161. else {
  82162. setTimeout(function () {
  82163. if (!_this._dataFetched) {
  82164. _this._cylinder.dispose();
  82165. }
  82166. }, 0);
  82167. }
  82168. };
  82169. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82170. if (impostor.mass === 0) {
  82171. return null;
  82172. }
  82173. if (!this._intersectsWithCylinder(impostor)) {
  82174. return null;
  82175. }
  82176. var impostorObjectCenter = impostor.getObjectCenter();
  82177. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82178. var direction = this._originDirection;
  82179. }
  82180. else {
  82181. var direction = impostorObjectCenter.subtract(this._originTop);
  82182. }
  82183. var multiplier = this._strength * -1;
  82184. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82185. return { force: force, contactPoint: impostorObjectCenter };
  82186. };
  82187. PhysicsUpdraftEvent.prototype._tick = function () {
  82188. var _this = this;
  82189. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82190. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82191. if (!impostorForceAndContactPoint) {
  82192. return;
  82193. }
  82194. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82195. });
  82196. };
  82197. /*** Helpers ***/
  82198. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82199. if (!this._cylinder) {
  82200. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82201. height: this._height,
  82202. diameter: this._radius * 2,
  82203. }, this._scene);
  82204. this._cylinder.isVisible = false;
  82205. }
  82206. };
  82207. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82208. var impostorObject = impostor.object;
  82209. this._prepareCylinder();
  82210. this._cylinder.position = this._cylinderPosition;
  82211. return this._cylinder.intersectsMesh(impostorObject, true);
  82212. };
  82213. return PhysicsUpdraftEvent;
  82214. }());
  82215. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82216. /***** Vortex *****/
  82217. var PhysicsVortexEvent = /** @class */ (function () {
  82218. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82219. this._scene = _scene;
  82220. this._origin = _origin;
  82221. this._radius = _radius;
  82222. this._strength = _strength;
  82223. this._height = _height;
  82224. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82225. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82226. this._updraftMultiplier = 0.02;
  82227. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82228. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82229. this._physicsEngine = this._scene.getPhysicsEngine();
  82230. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82231. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82232. this._tickCallback = this._tick.bind(this);
  82233. }
  82234. /**
  82235. * Returns the data related to the vortex event (cylinder).
  82236. * @returns {PhysicsVortexEventData}
  82237. */
  82238. PhysicsVortexEvent.prototype.getData = function () {
  82239. this._dataFetched = true;
  82240. return {
  82241. cylinder: this._cylinder,
  82242. };
  82243. };
  82244. /**
  82245. * Enables the vortex.
  82246. */
  82247. PhysicsVortexEvent.prototype.enable = function () {
  82248. this._tickCallback.call(this);
  82249. this._scene.registerBeforeRender(this._tickCallback);
  82250. };
  82251. /**
  82252. * Disables the cortex.
  82253. */
  82254. PhysicsVortexEvent.prototype.disable = function () {
  82255. this._scene.unregisterBeforeRender(this._tickCallback);
  82256. };
  82257. /**
  82258. * Disposes the sphere.
  82259. * @param {bolean} force
  82260. */
  82261. PhysicsVortexEvent.prototype.dispose = function (force) {
  82262. var _this = this;
  82263. if (force === void 0) { force = true; }
  82264. if (force) {
  82265. this._cylinder.dispose();
  82266. }
  82267. else {
  82268. setTimeout(function () {
  82269. if (!_this._dataFetched) {
  82270. _this._cylinder.dispose();
  82271. }
  82272. }, 0);
  82273. }
  82274. };
  82275. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82276. if (impostor.mass === 0) {
  82277. return null;
  82278. }
  82279. if (!this._intersectsWithCylinder(impostor)) {
  82280. return null;
  82281. }
  82282. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82283. return null;
  82284. }
  82285. var impostorObjectCenter = impostor.getObjectCenter();
  82286. 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)
  82287. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82288. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82289. var hit = ray.intersectsMesh(impostor.object);
  82290. var contactPoint = hit.pickedPoint;
  82291. if (!contactPoint) {
  82292. return null;
  82293. }
  82294. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82295. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82296. var directionToOrigin = contactPoint.normalize();
  82297. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82298. directionToOrigin = directionToOrigin.negate();
  82299. }
  82300. // TODO: find a more physically based solution
  82301. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82302. var forceX = directionToOrigin.x * this._strength / 8;
  82303. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82304. var forceZ = directionToOrigin.z * this._strength / 8;
  82305. }
  82306. else {
  82307. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82308. var forceY = this._originTop.y * this._updraftMultiplier;
  82309. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82310. }
  82311. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82312. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82313. return { force: force, contactPoint: impostorObjectCenter };
  82314. };
  82315. PhysicsVortexEvent.prototype._tick = function () {
  82316. var _this = this;
  82317. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82318. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82319. if (!impostorForceAndContactPoint) {
  82320. return;
  82321. }
  82322. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82323. });
  82324. };
  82325. /*** Helpers ***/
  82326. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82327. if (!this._cylinder) {
  82328. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82329. height: this._height,
  82330. diameter: this._radius * 2,
  82331. }, this._scene);
  82332. this._cylinder.isVisible = false;
  82333. }
  82334. };
  82335. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82336. var impostorObject = impostor.object;
  82337. this._prepareCylinder();
  82338. this._cylinder.position = this._cylinderPosition;
  82339. return this._cylinder.intersectsMesh(impostorObject, true);
  82340. };
  82341. return PhysicsVortexEvent;
  82342. }());
  82343. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82344. /***** Enums *****/
  82345. /**
  82346. * The strenght of the force in correspondence to the distance of the affected object
  82347. */
  82348. var PhysicsRadialImpulseFalloff;
  82349. (function (PhysicsRadialImpulseFalloff) {
  82350. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82351. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  82352. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82353. /**
  82354. * The strenght of the force in correspondence to the distance of the affected object
  82355. */
  82356. var PhysicsUpdraftMode;
  82357. (function (PhysicsUpdraftMode) {
  82358. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82359. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  82360. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82361. })(BABYLON || (BABYLON = {}));
  82362. //# sourceMappingURL=babylon.physicsHelper.js.map
  82363. var BABYLON;
  82364. (function (BABYLON) {
  82365. var CannonJSPlugin = /** @class */ (function () {
  82366. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82367. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82368. if (iterations === void 0) { iterations = 10; }
  82369. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82370. this.name = "CannonJSPlugin";
  82371. this._physicsMaterials = new Array();
  82372. this._fixedTimeStep = 1 / 60;
  82373. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82374. this.BJSCANNON = CANNON;
  82375. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82376. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82377. this._tmpPosition = BABYLON.Vector3.Zero();
  82378. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82379. this._tmpUnityRotation = new BABYLON.Quaternion();
  82380. if (!this.isSupported()) {
  82381. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82382. return;
  82383. }
  82384. this._extendNamespace();
  82385. this.world = new this.BJSCANNON.World();
  82386. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82387. this.world.solver.iterations = iterations;
  82388. }
  82389. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82390. this.world.gravity.copy(gravity);
  82391. };
  82392. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82393. this._fixedTimeStep = timeStep;
  82394. };
  82395. CannonJSPlugin.prototype.getTimeStep = function () {
  82396. return this._fixedTimeStep;
  82397. };
  82398. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82399. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82400. };
  82401. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82402. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82403. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82404. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82405. };
  82406. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82407. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82408. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82409. impostor.physicsBody.applyForce(impulse, worldPoint);
  82410. };
  82411. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82412. //parent-child relationship. Does this impostor has a parent impostor?
  82413. if (impostor.parent) {
  82414. if (impostor.physicsBody) {
  82415. this.removePhysicsBody(impostor);
  82416. //TODO is that needed?
  82417. impostor.forceUpdate();
  82418. }
  82419. return;
  82420. }
  82421. //should a new body be created for this impostor?
  82422. if (impostor.isBodyInitRequired()) {
  82423. var shape = this._createShape(impostor);
  82424. //unregister events, if body is being changed
  82425. var oldBody = impostor.physicsBody;
  82426. if (oldBody) {
  82427. this.removePhysicsBody(impostor);
  82428. }
  82429. //create the body and material
  82430. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82431. var bodyCreationObject = {
  82432. mass: impostor.getParam("mass"),
  82433. material: material
  82434. };
  82435. // A simple extend, in case native options were used.
  82436. var nativeOptions = impostor.getParam("nativeOptions");
  82437. for (var key in nativeOptions) {
  82438. if (nativeOptions.hasOwnProperty(key)) {
  82439. bodyCreationObject[key] = nativeOptions[key];
  82440. }
  82441. }
  82442. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82443. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82444. this.world.addEventListener("preStep", impostor.beforeStep);
  82445. this.world.addEventListener("postStep", impostor.afterStep);
  82446. impostor.physicsBody.addShape(shape);
  82447. this.world.add(impostor.physicsBody);
  82448. //try to keep the body moving in the right direction by taking old properties.
  82449. //Should be tested!
  82450. if (oldBody) {
  82451. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82452. impostor.physicsBody[param].copy(oldBody[param]);
  82453. });
  82454. }
  82455. this._processChildMeshes(impostor);
  82456. }
  82457. //now update the body's transformation
  82458. this._updatePhysicsBodyTransformation(impostor);
  82459. };
  82460. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82461. var _this = this;
  82462. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82463. var currentRotation = mainImpostor.object.rotationQuaternion;
  82464. if (meshChildren.length) {
  82465. var processMesh = function (localPosition, mesh) {
  82466. if (!currentRotation || !mesh.rotationQuaternion) {
  82467. return;
  82468. }
  82469. var childImpostor = mesh.getPhysicsImpostor();
  82470. if (childImpostor) {
  82471. var parent = childImpostor.parent;
  82472. if (parent !== mainImpostor) {
  82473. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82474. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82475. if (childImpostor.physicsBody) {
  82476. _this.removePhysicsBody(childImpostor);
  82477. childImpostor.physicsBody = null;
  82478. }
  82479. childImpostor.parent = mainImpostor;
  82480. childImpostor.resetUpdateFlags();
  82481. 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));
  82482. //Add the mass of the children.
  82483. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82484. }
  82485. }
  82486. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82487. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82488. };
  82489. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82490. }
  82491. };
  82492. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82493. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82494. this.world.removeEventListener("preStep", impostor.beforeStep);
  82495. this.world.removeEventListener("postStep", impostor.afterStep);
  82496. this.world.remove(impostor.physicsBody);
  82497. };
  82498. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82499. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82500. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82501. if (!mainBody || !connectedBody) {
  82502. return;
  82503. }
  82504. var constraint;
  82505. var jointData = impostorJoint.joint.jointData;
  82506. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82507. var constraintData = {
  82508. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82509. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82510. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82511. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82512. maxForce: jointData.nativeParams.maxForce,
  82513. collideConnected: !!jointData.collision
  82514. };
  82515. switch (impostorJoint.joint.type) {
  82516. case BABYLON.PhysicsJoint.HingeJoint:
  82517. case BABYLON.PhysicsJoint.Hinge2Joint:
  82518. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82519. break;
  82520. case BABYLON.PhysicsJoint.DistanceJoint:
  82521. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82522. break;
  82523. case BABYLON.PhysicsJoint.SpringJoint:
  82524. var springData = jointData;
  82525. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82526. restLength: springData.length,
  82527. stiffness: springData.stiffness,
  82528. damping: springData.damping,
  82529. localAnchorA: constraintData.pivotA,
  82530. localAnchorB: constraintData.pivotB
  82531. });
  82532. break;
  82533. case BABYLON.PhysicsJoint.LockJoint:
  82534. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82535. break;
  82536. case BABYLON.PhysicsJoint.PointToPointJoint:
  82537. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82538. default:
  82539. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82540. break;
  82541. }
  82542. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82543. constraint.collideConnected = !!jointData.collision;
  82544. impostorJoint.joint.physicsJoint = constraint;
  82545. //don't add spring as constraint, as it is not one.
  82546. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  82547. this.world.addConstraint(constraint);
  82548. }
  82549. else {
  82550. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  82551. constraint.applyForce();
  82552. });
  82553. }
  82554. };
  82555. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82556. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  82557. };
  82558. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  82559. var index;
  82560. var mat;
  82561. for (index = 0; index < this._physicsMaterials.length; index++) {
  82562. mat = this._physicsMaterials[index];
  82563. if (mat.friction === friction && mat.restitution === restitution) {
  82564. return mat;
  82565. }
  82566. }
  82567. var currentMat = new this.BJSCANNON.Material(name);
  82568. currentMat.friction = friction;
  82569. currentMat.restitution = restitution;
  82570. this._physicsMaterials.push(currentMat);
  82571. return currentMat;
  82572. };
  82573. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82574. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82575. };
  82576. CannonJSPlugin.prototype._createShape = function (impostor) {
  82577. var object = impostor.object;
  82578. var returnValue;
  82579. var extendSize = impostor.getObjectExtendSize();
  82580. switch (impostor.type) {
  82581. case BABYLON.PhysicsImpostor.SphereImpostor:
  82582. var radiusX = extendSize.x;
  82583. var radiusY = extendSize.y;
  82584. var radiusZ = extendSize.z;
  82585. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82586. break;
  82587. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82588. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82589. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82590. break;
  82591. case BABYLON.PhysicsImpostor.BoxImpostor:
  82592. var box = extendSize.scale(0.5);
  82593. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82594. break;
  82595. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82596. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82597. returnValue = new this.BJSCANNON.Plane();
  82598. break;
  82599. case BABYLON.PhysicsImpostor.MeshImpostor:
  82600. // should transform the vertex data to world coordinates!!
  82601. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82602. var rawFaces = object.getIndices ? object.getIndices() : [];
  82603. if (!rawVerts)
  82604. return;
  82605. // get only scale! so the object could transform correctly.
  82606. var oldPosition = object.position.clone();
  82607. var oldRotation = object.rotation && object.rotation.clone();
  82608. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82609. object.position.copyFromFloats(0, 0, 0);
  82610. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82611. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82612. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82613. var transform = object.computeWorldMatrix(true);
  82614. // convert rawVerts to object space
  82615. var temp = new Array();
  82616. var index;
  82617. for (index = 0; index < rawVerts.length; index += 3) {
  82618. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82619. }
  82620. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82621. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82622. //now set back the transformation!
  82623. object.position.copyFrom(oldPosition);
  82624. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82625. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82626. break;
  82627. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82628. var oldPosition2 = object.position.clone();
  82629. var oldRotation2 = object.rotation && object.rotation.clone();
  82630. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82631. object.position.copyFromFloats(0, 0, 0);
  82632. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82633. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82634. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82635. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82636. returnValue = this._createHeightmap(object);
  82637. object.position.copyFrom(oldPosition2);
  82638. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82639. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82640. object.computeWorldMatrix(true);
  82641. break;
  82642. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82643. returnValue = new this.BJSCANNON.Particle();
  82644. break;
  82645. }
  82646. return returnValue;
  82647. };
  82648. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82649. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82650. var transform = object.computeWorldMatrix(true);
  82651. // convert rawVerts to object space
  82652. var temp = new Array();
  82653. var index;
  82654. for (index = 0; index < pos.length; index += 3) {
  82655. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82656. }
  82657. pos = temp;
  82658. var matrix = new Array();
  82659. //For now pointDepth will not be used and will be automatically calculated.
  82660. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82661. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82662. var boundingInfo = object.getBoundingInfo();
  82663. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82664. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82665. var elementSize = dim * 2 / arraySize;
  82666. for (var i = 0; i < pos.length; i = i + 3) {
  82667. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82668. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82669. var y = -pos[i + 2] + minY;
  82670. if (!matrix[x]) {
  82671. matrix[x] = [];
  82672. }
  82673. if (!matrix[x][z]) {
  82674. matrix[x][z] = y;
  82675. }
  82676. matrix[x][z] = Math.max(y, matrix[x][z]);
  82677. }
  82678. for (var x = 0; x <= arraySize; ++x) {
  82679. if (!matrix[x]) {
  82680. var loc = 1;
  82681. while (!matrix[(x + loc) % arraySize]) {
  82682. loc++;
  82683. }
  82684. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82685. //console.log("missing x", x);
  82686. }
  82687. for (var z = 0; z <= arraySize; ++z) {
  82688. if (!matrix[x][z]) {
  82689. var loc = 1;
  82690. var newValue;
  82691. while (newValue === undefined) {
  82692. newValue = matrix[x][(z + loc++) % arraySize];
  82693. }
  82694. matrix[x][z] = newValue;
  82695. }
  82696. }
  82697. }
  82698. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82699. elementSize: elementSize
  82700. });
  82701. //For future reference, needed for body transformation
  82702. shape.minY = minY;
  82703. return shape;
  82704. };
  82705. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82706. var object = impostor.object;
  82707. //make sure it is updated...
  82708. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82709. // The delta between the mesh position and the mesh bounding box center
  82710. var bInfo = object.getBoundingInfo();
  82711. if (!bInfo)
  82712. return;
  82713. var center = impostor.getObjectCenter();
  82714. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82715. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82716. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82717. this._tmpPosition.copyFrom(center);
  82718. var quaternion = object.rotationQuaternion;
  82719. if (!quaternion) {
  82720. return;
  82721. }
  82722. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82723. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82724. //-90 DEG in X, precalculated
  82725. quaternion = quaternion.multiply(this._minus90X);
  82726. //Invert! (Precalculated, 90 deg in X)
  82727. //No need to clone. this will never change.
  82728. impostor.setDeltaRotation(this._plus90X);
  82729. }
  82730. //If it is a heightfield, if should be centered.
  82731. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82732. var mesh = object;
  82733. var boundingInfo = mesh.getBoundingInfo();
  82734. //calculate the correct body position:
  82735. var rotationQuaternion = mesh.rotationQuaternion;
  82736. mesh.rotationQuaternion = this._tmpUnityRotation;
  82737. mesh.computeWorldMatrix(true);
  82738. //get original center with no rotation
  82739. var c = center.clone();
  82740. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82741. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82742. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82743. mesh.setPreTransformMatrix(p);
  82744. mesh.computeWorldMatrix(true);
  82745. //calculate the translation
  82746. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82747. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82748. //add it inverted to the delta
  82749. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82750. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82751. //rotation is back
  82752. mesh.rotationQuaternion = rotationQuaternion;
  82753. mesh.setPreTransformMatrix(oldPivot);
  82754. mesh.computeWorldMatrix(true);
  82755. }
  82756. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82757. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82758. //this._tmpPosition.copyFrom(object.position);
  82759. }
  82760. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82761. //Now update the impostor object
  82762. impostor.physicsBody.position.copy(this._tmpPosition);
  82763. impostor.physicsBody.quaternion.copy(quaternion);
  82764. };
  82765. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82766. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82767. if (impostor.object.rotationQuaternion) {
  82768. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82769. }
  82770. };
  82771. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82772. impostor.physicsBody.position.copy(newPosition);
  82773. impostor.physicsBody.quaternion.copy(newRotation);
  82774. };
  82775. CannonJSPlugin.prototype.isSupported = function () {
  82776. return this.BJSCANNON !== undefined;
  82777. };
  82778. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82779. impostor.physicsBody.velocity.copy(velocity);
  82780. };
  82781. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82782. impostor.physicsBody.angularVelocity.copy(velocity);
  82783. };
  82784. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82785. var v = impostor.physicsBody.velocity;
  82786. if (!v) {
  82787. return null;
  82788. }
  82789. return new BABYLON.Vector3(v.x, v.y, v.z);
  82790. };
  82791. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82792. var v = impostor.physicsBody.angularVelocity;
  82793. if (!v) {
  82794. return null;
  82795. }
  82796. return new BABYLON.Vector3(v.x, v.y, v.z);
  82797. };
  82798. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82799. impostor.physicsBody.mass = mass;
  82800. impostor.physicsBody.updateMassProperties();
  82801. };
  82802. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82803. return impostor.physicsBody.mass;
  82804. };
  82805. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82806. return impostor.physicsBody.material.friction;
  82807. };
  82808. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82809. impostor.physicsBody.material.friction = friction;
  82810. };
  82811. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82812. return impostor.physicsBody.material.restitution;
  82813. };
  82814. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82815. impostor.physicsBody.material.restitution = restitution;
  82816. };
  82817. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82818. impostor.physicsBody.sleep();
  82819. };
  82820. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82821. impostor.physicsBody.wakeUp();
  82822. };
  82823. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82824. joint.physicsJoint.distance = maxDistance;
  82825. };
  82826. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82827. // if (!motorIndex) {
  82828. // joint.physicsJoint.enableMotor();
  82829. // }
  82830. // }
  82831. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82832. // if (!motorIndex) {
  82833. // joint.physicsJoint.disableMotor();
  82834. // }
  82835. // }
  82836. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82837. if (!motorIndex) {
  82838. joint.physicsJoint.enableMotor();
  82839. joint.physicsJoint.setMotorSpeed(speed);
  82840. if (maxForce) {
  82841. this.setLimit(joint, maxForce);
  82842. }
  82843. }
  82844. };
  82845. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  82846. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  82847. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  82848. };
  82849. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  82850. var body = impostor.physicsBody;
  82851. mesh.position.x = body.position.x;
  82852. mesh.position.y = body.position.y;
  82853. mesh.position.z = body.position.z;
  82854. if (mesh.rotationQuaternion) {
  82855. mesh.rotationQuaternion.x = body.quaternion.x;
  82856. mesh.rotationQuaternion.y = body.quaternion.y;
  82857. mesh.rotationQuaternion.z = body.quaternion.z;
  82858. mesh.rotationQuaternion.w = body.quaternion.w;
  82859. }
  82860. };
  82861. CannonJSPlugin.prototype.getRadius = function (impostor) {
  82862. var shape = impostor.physicsBody.shapes[0];
  82863. return shape.boundingSphereRadius;
  82864. };
  82865. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  82866. var shape = impostor.physicsBody.shapes[0];
  82867. result.x = shape.halfExtents.x * 2;
  82868. result.y = shape.halfExtents.y * 2;
  82869. result.z = shape.halfExtents.z * 2;
  82870. };
  82871. CannonJSPlugin.prototype.dispose = function () {
  82872. };
  82873. CannonJSPlugin.prototype._extendNamespace = function () {
  82874. //this will force cannon to execute at least one step when using interpolation
  82875. var step_tmp1 = new this.BJSCANNON.Vec3();
  82876. var Engine = this.BJSCANNON;
  82877. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  82878. maxSubSteps = maxSubSteps || 10;
  82879. timeSinceLastCalled = timeSinceLastCalled || 0;
  82880. if (timeSinceLastCalled === 0) {
  82881. this.internalStep(dt);
  82882. this.time += dt;
  82883. }
  82884. else {
  82885. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  82886. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  82887. var t0 = performance.now();
  82888. for (var i = 0; i !== internalSteps; i++) {
  82889. this.internalStep(dt);
  82890. if (performance.now() - t0 > dt * 1000) {
  82891. break;
  82892. }
  82893. }
  82894. this.time += timeSinceLastCalled;
  82895. var h = this.time % dt;
  82896. var h_div_dt = h / dt;
  82897. var interpvelo = step_tmp1;
  82898. var bodies = this.bodies;
  82899. for (var j = 0; j !== bodies.length; j++) {
  82900. var b = bodies[j];
  82901. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  82902. b.position.vsub(b.previousPosition, interpvelo);
  82903. interpvelo.scale(h_div_dt, interpvelo);
  82904. b.position.vadd(interpvelo, b.interpolatedPosition);
  82905. }
  82906. else {
  82907. b.interpolatedPosition.copy(b.position);
  82908. b.interpolatedQuaternion.copy(b.quaternion);
  82909. }
  82910. }
  82911. }
  82912. };
  82913. };
  82914. return CannonJSPlugin;
  82915. }());
  82916. BABYLON.CannonJSPlugin = CannonJSPlugin;
  82917. })(BABYLON || (BABYLON = {}));
  82918. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  82919. var BABYLON;
  82920. (function (BABYLON) {
  82921. var OimoJSPlugin = /** @class */ (function () {
  82922. function OimoJSPlugin(iterations) {
  82923. this.name = "OimoJSPlugin";
  82924. this._tmpImpostorsArray = [];
  82925. this._tmpPositionVector = BABYLON.Vector3.Zero();
  82926. this.BJSOIMO = OIMO;
  82927. this.world = new this.BJSOIMO.World({
  82928. iterations: iterations
  82929. });
  82930. this.world.clear();
  82931. }
  82932. OimoJSPlugin.prototype.setGravity = function (gravity) {
  82933. this.world.gravity.copy(gravity);
  82934. };
  82935. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  82936. this.world.timeStep = timeStep;
  82937. };
  82938. OimoJSPlugin.prototype.getTimeStep = function () {
  82939. return this.world.timeStep;
  82940. };
  82941. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  82942. var _this = this;
  82943. impostors.forEach(function (impostor) {
  82944. impostor.beforeStep();
  82945. });
  82946. this.world.step();
  82947. impostors.forEach(function (impostor) {
  82948. impostor.afterStep();
  82949. //update the ordered impostors array
  82950. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  82951. });
  82952. //check for collisions
  82953. var contact = this.world.contacts;
  82954. while (contact !== null) {
  82955. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  82956. contact = contact.next;
  82957. continue;
  82958. }
  82959. //is this body colliding with any other? get the impostor
  82960. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  82961. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  82962. if (!mainImpostor || !collidingImpostor) {
  82963. contact = contact.next;
  82964. continue;
  82965. }
  82966. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  82967. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  82968. contact = contact.next;
  82969. }
  82970. };
  82971. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82972. var mass = impostor.physicsBody.mass;
  82973. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  82974. };
  82975. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82976. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  82977. this.applyImpulse(impostor, force, contactPoint);
  82978. };
  82979. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82980. var _this = this;
  82981. //parent-child relationship. Does this impostor has a parent impostor?
  82982. if (impostor.parent) {
  82983. if (impostor.physicsBody) {
  82984. this.removePhysicsBody(impostor);
  82985. //TODO is that needed?
  82986. impostor.forceUpdate();
  82987. }
  82988. return;
  82989. }
  82990. if (impostor.isBodyInitRequired()) {
  82991. var bodyConfig = {
  82992. name: impostor.uniqueId,
  82993. //Oimo must have mass, also for static objects.
  82994. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  82995. size: [],
  82996. type: [],
  82997. pos: [],
  82998. posShape: [],
  82999. rot: [],
  83000. rotShape: [],
  83001. move: impostor.getParam("mass") !== 0,
  83002. density: impostor.getParam("mass"),
  83003. friction: impostor.getParam("friction"),
  83004. restitution: impostor.getParam("restitution"),
  83005. //Supporting older versions of Oimo
  83006. world: this.world
  83007. };
  83008. var impostors = [impostor];
  83009. var addToArray = function (parent) {
  83010. if (!parent.getChildMeshes)
  83011. return;
  83012. parent.getChildMeshes().forEach(function (m) {
  83013. if (m.physicsImpostor) {
  83014. impostors.push(m.physicsImpostor);
  83015. //m.physicsImpostor._init();
  83016. }
  83017. });
  83018. };
  83019. addToArray(impostor.object);
  83020. var checkWithEpsilon_1 = function (value) {
  83021. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83022. };
  83023. impostors.forEach(function (i) {
  83024. if (!i.object.rotationQuaternion) {
  83025. return;
  83026. }
  83027. //get the correct bounding box
  83028. var oldQuaternion = i.object.rotationQuaternion;
  83029. var rot = oldQuaternion.toEulerAngles();
  83030. var extendSize = i.getObjectExtendSize();
  83031. var radToDeg = 57.295779513082320876;
  83032. if (i === impostor) {
  83033. var center = impostor.getObjectCenter();
  83034. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83035. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83036. //Can also use Array.prototype.push.apply
  83037. bodyConfig.pos.push(center.x);
  83038. bodyConfig.pos.push(center.y);
  83039. bodyConfig.pos.push(center.z);
  83040. bodyConfig.posShape.push(0, 0, 0);
  83041. //tmp solution
  83042. bodyConfig.rot.push(rot.x * radToDeg);
  83043. bodyConfig.rot.push(rot.y * radToDeg);
  83044. bodyConfig.rot.push(rot.z * radToDeg);
  83045. bodyConfig.rotShape.push(0, 0, 0);
  83046. }
  83047. else {
  83048. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83049. bodyConfig.posShape.push(localPosition.x);
  83050. bodyConfig.posShape.push(localPosition.y);
  83051. bodyConfig.posShape.push(localPosition.z);
  83052. bodyConfig.pos.push(0, 0, 0);
  83053. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83054. bodyConfig.rot.push(0);
  83055. bodyConfig.rot.push(0);
  83056. bodyConfig.rot.push(0);
  83057. bodyConfig.rotShape.push(rot.x * radToDeg);
  83058. bodyConfig.rotShape.push(rot.y * radToDeg);
  83059. bodyConfig.rotShape.push(rot.z * radToDeg);
  83060. }
  83061. // register mesh
  83062. switch (i.type) {
  83063. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83064. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83065. case BABYLON.PhysicsImpostor.SphereImpostor:
  83066. var radiusX = extendSize.x;
  83067. var radiusY = extendSize.y;
  83068. var radiusZ = extendSize.z;
  83069. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83070. bodyConfig.type.push('sphere');
  83071. //due to the way oimo works with compounds, add 3 times
  83072. bodyConfig.size.push(size);
  83073. bodyConfig.size.push(size);
  83074. bodyConfig.size.push(size);
  83075. break;
  83076. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83077. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83078. var sizeY = checkWithEpsilon_1(extendSize.y);
  83079. bodyConfig.type.push('cylinder');
  83080. bodyConfig.size.push(sizeX);
  83081. bodyConfig.size.push(sizeY);
  83082. //due to the way oimo works with compounds, add one more value.
  83083. bodyConfig.size.push(sizeY);
  83084. break;
  83085. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83086. case BABYLON.PhysicsImpostor.BoxImpostor:
  83087. default:
  83088. var sizeX = checkWithEpsilon_1(extendSize.x);
  83089. var sizeY = checkWithEpsilon_1(extendSize.y);
  83090. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83091. bodyConfig.type.push('box');
  83092. //if (i === impostor) {
  83093. bodyConfig.size.push(sizeX);
  83094. bodyConfig.size.push(sizeY);
  83095. bodyConfig.size.push(sizeZ);
  83096. //} else {
  83097. // bodyConfig.size.push(0,0,0);
  83098. //}
  83099. break;
  83100. }
  83101. //actually not needed, but hey...
  83102. i.object.rotationQuaternion = oldQuaternion;
  83103. });
  83104. impostor.physicsBody = this.world.add(bodyConfig);
  83105. }
  83106. else {
  83107. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83108. }
  83109. impostor.setDeltaPosition(this._tmpPositionVector);
  83110. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83111. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83112. };
  83113. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83114. //impostor.physicsBody.dispose();
  83115. //Same as : (older oimo versions)
  83116. this.world.removeRigidBody(impostor.physicsBody);
  83117. };
  83118. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83119. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83120. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83121. if (!mainBody || !connectedBody) {
  83122. return;
  83123. }
  83124. var jointData = impostorJoint.joint.jointData;
  83125. var options = jointData.nativeParams || {};
  83126. var type;
  83127. var nativeJointData = {
  83128. body1: mainBody,
  83129. body2: connectedBody,
  83130. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83131. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83132. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83133. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83134. min: options.min,
  83135. max: options.max,
  83136. collision: options.collision || jointData.collision,
  83137. spring: options.spring,
  83138. //supporting older version of Oimo
  83139. world: this.world
  83140. };
  83141. switch (impostorJoint.joint.type) {
  83142. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83143. type = "jointBall";
  83144. break;
  83145. case BABYLON.PhysicsJoint.SpringJoint:
  83146. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83147. var springData = jointData;
  83148. nativeJointData.min = springData.length || nativeJointData.min;
  83149. //Max should also be set, just make sure it is at least min
  83150. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83151. case BABYLON.PhysicsJoint.DistanceJoint:
  83152. type = "jointDistance";
  83153. nativeJointData.max = jointData.maxDistance;
  83154. break;
  83155. case BABYLON.PhysicsJoint.PrismaticJoint:
  83156. type = "jointPrisme";
  83157. break;
  83158. case BABYLON.PhysicsJoint.SliderJoint:
  83159. type = "jointSlide";
  83160. break;
  83161. case BABYLON.PhysicsJoint.WheelJoint:
  83162. type = "jointWheel";
  83163. break;
  83164. case BABYLON.PhysicsJoint.HingeJoint:
  83165. default:
  83166. type = "jointHinge";
  83167. break;
  83168. }
  83169. nativeJointData.type = type;
  83170. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83171. };
  83172. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83173. //Bug in Oimo prevents us from disposing a joint in the playground
  83174. //joint.joint.physicsJoint.dispose();
  83175. //So we will bruteforce it!
  83176. try {
  83177. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83178. }
  83179. catch (e) {
  83180. BABYLON.Tools.Warn(e);
  83181. }
  83182. };
  83183. OimoJSPlugin.prototype.isSupported = function () {
  83184. return this.BJSOIMO !== undefined;
  83185. };
  83186. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83187. if (!impostor.physicsBody.sleeping) {
  83188. //TODO check that
  83189. /*if (impostor.physicsBody.shapes.next) {
  83190. var parentShape = this._getLastShape(impostor.physicsBody);
  83191. impostor.object.position.copyFrom(parentShape.position);
  83192. console.log(parentShape.position);
  83193. } else {*/
  83194. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83195. //}
  83196. if (impostor.object.rotationQuaternion) {
  83197. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83198. }
  83199. }
  83200. };
  83201. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83202. var body = impostor.physicsBody;
  83203. body.position.copy(newPosition);
  83204. body.orientation.copy(newRotation);
  83205. body.syncShapes();
  83206. body.awake();
  83207. };
  83208. /*private _getLastShape(body: any): any {
  83209. var lastShape = body.shapes;
  83210. while (lastShape.next) {
  83211. lastShape = lastShape.next;
  83212. }
  83213. return lastShape;
  83214. }*/
  83215. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83216. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83217. };
  83218. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83219. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83220. };
  83221. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83222. var v = impostor.physicsBody.linearVelocity;
  83223. if (!v) {
  83224. return null;
  83225. }
  83226. return new BABYLON.Vector3(v.x, v.y, v.z);
  83227. };
  83228. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83229. var v = impostor.physicsBody.angularVelocity;
  83230. if (!v) {
  83231. return null;
  83232. }
  83233. return new BABYLON.Vector3(v.x, v.y, v.z);
  83234. };
  83235. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83236. var staticBody = mass === 0;
  83237. //this will actually set the body's density and not its mass.
  83238. //But this is how oimo treats the mass variable.
  83239. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83240. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83241. };
  83242. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83243. return impostor.physicsBody.shapes.density;
  83244. };
  83245. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83246. return impostor.physicsBody.shapes.friction;
  83247. };
  83248. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83249. impostor.physicsBody.shapes.friction = friction;
  83250. };
  83251. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83252. return impostor.physicsBody.shapes.restitution;
  83253. };
  83254. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83255. impostor.physicsBody.shapes.restitution = restitution;
  83256. };
  83257. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83258. impostor.physicsBody.sleep();
  83259. };
  83260. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83261. impostor.physicsBody.awake();
  83262. };
  83263. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83264. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83265. if (minDistance !== void 0) {
  83266. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83267. }
  83268. };
  83269. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83270. //TODO separate rotational and transational motors.
  83271. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83272. if (motor) {
  83273. motor.setMotor(speed, maxForce);
  83274. }
  83275. };
  83276. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83277. //TODO separate rotational and transational motors.
  83278. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83279. if (motor) {
  83280. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83281. }
  83282. };
  83283. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83284. var body = impostor.physicsBody;
  83285. mesh.position.x = body.position.x;
  83286. mesh.position.y = body.position.y;
  83287. mesh.position.z = body.position.z;
  83288. if (mesh.rotationQuaternion) {
  83289. mesh.rotationQuaternion.x = body.orientation.x;
  83290. mesh.rotationQuaternion.y = body.orientation.y;
  83291. mesh.rotationQuaternion.z = body.orientation.z;
  83292. mesh.rotationQuaternion.w = body.orientation.s;
  83293. }
  83294. };
  83295. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83296. return impostor.physicsBody.shapes.radius;
  83297. };
  83298. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83299. var shape = impostor.physicsBody.shapes;
  83300. result.x = shape.halfWidth * 2;
  83301. result.y = shape.halfHeight * 2;
  83302. result.z = shape.halfDepth * 2;
  83303. };
  83304. OimoJSPlugin.prototype.dispose = function () {
  83305. this.world.clear();
  83306. };
  83307. return OimoJSPlugin;
  83308. }());
  83309. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83310. })(BABYLON || (BABYLON = {}));
  83311. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83312. var BABYLON;
  83313. (function (BABYLON) {
  83314. /*
  83315. * Based on jsTGALoader - Javascript loader for TGA file
  83316. * By Vincent Thibault
  83317. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83318. */
  83319. var TGATools = /** @class */ (function () {
  83320. function TGATools() {
  83321. }
  83322. TGATools.GetTGAHeader = function (data) {
  83323. var offset = 0;
  83324. var header = {
  83325. id_length: data[offset++],
  83326. colormap_type: data[offset++],
  83327. image_type: data[offset++],
  83328. colormap_index: data[offset++] | data[offset++] << 8,
  83329. colormap_length: data[offset++] | data[offset++] << 8,
  83330. colormap_size: data[offset++],
  83331. origin: [
  83332. data[offset++] | data[offset++] << 8,
  83333. data[offset++] | data[offset++] << 8
  83334. ],
  83335. width: data[offset++] | data[offset++] << 8,
  83336. height: data[offset++] | data[offset++] << 8,
  83337. pixel_size: data[offset++],
  83338. flags: data[offset++]
  83339. };
  83340. return header;
  83341. };
  83342. TGATools.UploadContent = function (gl, data) {
  83343. // Not enough data to contain header ?
  83344. if (data.length < 19) {
  83345. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83346. return;
  83347. }
  83348. // Read Header
  83349. var offset = 18;
  83350. var header = TGATools.GetTGAHeader(data);
  83351. // Assume it's a valid Targa file.
  83352. if (header.id_length + offset > data.length) {
  83353. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83354. return;
  83355. }
  83356. // Skip not needed data
  83357. offset += header.id_length;
  83358. var use_rle = false;
  83359. var use_pal = false;
  83360. var use_grey = false;
  83361. // Get some informations.
  83362. switch (header.image_type) {
  83363. case TGATools._TYPE_RLE_INDEXED:
  83364. use_rle = true;
  83365. case TGATools._TYPE_INDEXED:
  83366. use_pal = true;
  83367. break;
  83368. case TGATools._TYPE_RLE_RGB:
  83369. use_rle = true;
  83370. case TGATools._TYPE_RGB:
  83371. // use_rgb = true;
  83372. break;
  83373. case TGATools._TYPE_RLE_GREY:
  83374. use_rle = true;
  83375. case TGATools._TYPE_GREY:
  83376. use_grey = true;
  83377. break;
  83378. }
  83379. var pixel_data;
  83380. // var numAlphaBits = header.flags & 0xf;
  83381. var pixel_size = header.pixel_size >> 3;
  83382. var pixel_total = header.width * header.height * pixel_size;
  83383. // Read palettes
  83384. var palettes;
  83385. if (use_pal) {
  83386. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83387. }
  83388. // Read LRE
  83389. if (use_rle) {
  83390. pixel_data = new Uint8Array(pixel_total);
  83391. var c, count, i;
  83392. var localOffset = 0;
  83393. var pixels = new Uint8Array(pixel_size);
  83394. while (offset < pixel_total && localOffset < pixel_total) {
  83395. c = data[offset++];
  83396. count = (c & 0x7f) + 1;
  83397. // RLE pixels
  83398. if (c & 0x80) {
  83399. // Bind pixel tmp array
  83400. for (i = 0; i < pixel_size; ++i) {
  83401. pixels[i] = data[offset++];
  83402. }
  83403. // Copy pixel array
  83404. for (i = 0; i < count; ++i) {
  83405. pixel_data.set(pixels, localOffset + i * pixel_size);
  83406. }
  83407. localOffset += pixel_size * count;
  83408. }
  83409. // Raw pixels
  83410. else {
  83411. count *= pixel_size;
  83412. for (i = 0; i < count; ++i) {
  83413. pixel_data[localOffset + i] = data[offset++];
  83414. }
  83415. localOffset += count;
  83416. }
  83417. }
  83418. }
  83419. // RAW Pixels
  83420. else {
  83421. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83422. }
  83423. // Load to texture
  83424. var x_start, y_start, x_step, y_step, y_end, x_end;
  83425. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83426. default:
  83427. case TGATools._ORIGIN_UL:
  83428. x_start = 0;
  83429. x_step = 1;
  83430. x_end = header.width;
  83431. y_start = 0;
  83432. y_step = 1;
  83433. y_end = header.height;
  83434. break;
  83435. case TGATools._ORIGIN_BL:
  83436. x_start = 0;
  83437. x_step = 1;
  83438. x_end = header.width;
  83439. y_start = header.height - 1;
  83440. y_step = -1;
  83441. y_end = -1;
  83442. break;
  83443. case TGATools._ORIGIN_UR:
  83444. x_start = header.width - 1;
  83445. x_step = -1;
  83446. x_end = -1;
  83447. y_start = 0;
  83448. y_step = 1;
  83449. y_end = header.height;
  83450. break;
  83451. case TGATools._ORIGIN_BR:
  83452. x_start = header.width - 1;
  83453. x_step = -1;
  83454. x_end = -1;
  83455. y_start = header.height - 1;
  83456. y_step = -1;
  83457. y_end = -1;
  83458. break;
  83459. }
  83460. // Load the specify method
  83461. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83462. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83463. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83464. };
  83465. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83466. var image = pixel_data, colormap = palettes;
  83467. var width = header.width, height = header.height;
  83468. var color, i = 0, x, y;
  83469. var imageData = new Uint8Array(width * height * 4);
  83470. for (y = y_start; y !== y_end; y += y_step) {
  83471. for (x = x_start; x !== x_end; x += x_step, i++) {
  83472. color = image[i];
  83473. imageData[(x + width * y) * 4 + 3] = 255;
  83474. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83475. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83476. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83477. }
  83478. }
  83479. return imageData;
  83480. };
  83481. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83482. var image = pixel_data;
  83483. var width = header.width, height = header.height;
  83484. var color, i = 0, x, y;
  83485. var imageData = new Uint8Array(width * height * 4);
  83486. for (y = y_start; y !== y_end; y += y_step) {
  83487. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83488. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83489. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83490. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83491. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83492. imageData[(x + width * y) * 4 + 0] = r;
  83493. imageData[(x + width * y) * 4 + 1] = g;
  83494. imageData[(x + width * y) * 4 + 2] = b;
  83495. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83496. }
  83497. }
  83498. return imageData;
  83499. };
  83500. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83501. var image = pixel_data;
  83502. var width = header.width, height = header.height;
  83503. var i = 0, x, y;
  83504. var imageData = new Uint8Array(width * height * 4);
  83505. for (y = y_start; y !== y_end; y += y_step) {
  83506. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83507. imageData[(x + width * y) * 4 + 3] = 255;
  83508. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83509. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83510. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83511. }
  83512. }
  83513. return imageData;
  83514. };
  83515. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83516. var image = pixel_data;
  83517. var width = header.width, height = header.height;
  83518. var i = 0, x, y;
  83519. var imageData = new Uint8Array(width * height * 4);
  83520. for (y = y_start; y !== y_end; y += y_step) {
  83521. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83522. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83523. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83524. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83525. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83526. }
  83527. }
  83528. return imageData;
  83529. };
  83530. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83531. var image = pixel_data;
  83532. var width = header.width, height = header.height;
  83533. var color, i = 0, x, y;
  83534. var imageData = new Uint8Array(width * height * 4);
  83535. for (y = y_start; y !== y_end; y += y_step) {
  83536. for (x = x_start; x !== x_end; x += x_step, i++) {
  83537. color = image[i];
  83538. imageData[(x + width * y) * 4 + 0] = color;
  83539. imageData[(x + width * y) * 4 + 1] = color;
  83540. imageData[(x + width * y) * 4 + 2] = color;
  83541. imageData[(x + width * y) * 4 + 3] = 255;
  83542. }
  83543. }
  83544. return imageData;
  83545. };
  83546. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83547. var image = pixel_data;
  83548. var width = header.width, height = header.height;
  83549. var i = 0, x, y;
  83550. var imageData = new Uint8Array(width * height * 4);
  83551. for (y = y_start; y !== y_end; y += y_step) {
  83552. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83553. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  83554. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  83555. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83556. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  83557. }
  83558. }
  83559. return imageData;
  83560. };
  83561. //private static _TYPE_NO_DATA = 0;
  83562. TGATools._TYPE_INDEXED = 1;
  83563. TGATools._TYPE_RGB = 2;
  83564. TGATools._TYPE_GREY = 3;
  83565. TGATools._TYPE_RLE_INDEXED = 9;
  83566. TGATools._TYPE_RLE_RGB = 10;
  83567. TGATools._TYPE_RLE_GREY = 11;
  83568. TGATools._ORIGIN_MASK = 0x30;
  83569. TGATools._ORIGIN_SHIFT = 0x04;
  83570. TGATools._ORIGIN_BL = 0x00;
  83571. TGATools._ORIGIN_BR = 0x01;
  83572. TGATools._ORIGIN_UL = 0x02;
  83573. TGATools._ORIGIN_UR = 0x03;
  83574. return TGATools;
  83575. }());
  83576. BABYLON.TGATools = TGATools;
  83577. })(BABYLON || (BABYLON = {}));
  83578. //# sourceMappingURL=babylon.tga.js.map
  83579. var BABYLON;
  83580. (function (BABYLON) {
  83581. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83582. // All values and structures referenced from:
  83583. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83584. var DDS_MAGIC = 0x20534444;
  83585. var
  83586. //DDSD_CAPS = 0x1,
  83587. //DDSD_HEIGHT = 0x2,
  83588. //DDSD_WIDTH = 0x4,
  83589. //DDSD_PITCH = 0x8,
  83590. //DDSD_PIXELFORMAT = 0x1000,
  83591. DDSD_MIPMAPCOUNT = 0x20000;
  83592. //DDSD_LINEARSIZE = 0x80000,
  83593. //DDSD_DEPTH = 0x800000;
  83594. // var DDSCAPS_COMPLEX = 0x8,
  83595. // DDSCAPS_MIPMAP = 0x400000,
  83596. // DDSCAPS_TEXTURE = 0x1000;
  83597. var DDSCAPS2_CUBEMAP = 0x200;
  83598. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83599. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83600. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83601. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83602. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83603. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83604. // DDSCAPS2_VOLUME = 0x200000;
  83605. var
  83606. //DDPF_ALPHAPIXELS = 0x1,
  83607. //DDPF_ALPHA = 0x2,
  83608. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83609. //DDPF_YUV = 0x200,
  83610. DDPF_LUMINANCE = 0x20000;
  83611. function FourCCToInt32(value) {
  83612. return value.charCodeAt(0) +
  83613. (value.charCodeAt(1) << 8) +
  83614. (value.charCodeAt(2) << 16) +
  83615. (value.charCodeAt(3) << 24);
  83616. }
  83617. function Int32ToFourCC(value) {
  83618. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83619. }
  83620. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83621. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83622. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83623. var FOURCC_DX10 = FourCCToInt32("DX10");
  83624. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83625. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83626. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83627. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83628. var headerLengthInt = 31; // The header length in 32 bit ints
  83629. // Offsets into the header array
  83630. var off_magic = 0;
  83631. var off_size = 1;
  83632. var off_flags = 2;
  83633. var off_height = 3;
  83634. var off_width = 4;
  83635. var off_mipmapCount = 7;
  83636. var off_pfFlags = 20;
  83637. var off_pfFourCC = 21;
  83638. var off_RGBbpp = 22;
  83639. var off_RMask = 23;
  83640. var off_GMask = 24;
  83641. var off_BMask = 25;
  83642. var off_AMask = 26;
  83643. // var off_caps1 = 27;
  83644. var off_caps2 = 28;
  83645. // var off_caps3 = 29;
  83646. // var off_caps4 = 30;
  83647. var off_dxgiFormat = 32;
  83648. ;
  83649. var DDSTools = /** @class */ (function () {
  83650. function DDSTools() {
  83651. }
  83652. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83653. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83654. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83655. var mipmapCount = 1;
  83656. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83657. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83658. }
  83659. var fourCC = header[off_pfFourCC];
  83660. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83661. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83662. switch (fourCC) {
  83663. case FOURCC_D3DFMT_R16G16B16A16F:
  83664. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83665. break;
  83666. case FOURCC_D3DFMT_R32G32B32A32F:
  83667. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83668. break;
  83669. case FOURCC_DX10:
  83670. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83671. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83672. break;
  83673. }
  83674. }
  83675. return {
  83676. width: header[off_width],
  83677. height: header[off_height],
  83678. mipmapCount: mipmapCount,
  83679. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83680. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83681. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83682. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83683. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83684. dxgiFormat: dxgiFormat,
  83685. textureType: textureType
  83686. };
  83687. };
  83688. DDSTools._ToHalfFloat = function (value) {
  83689. if (!DDSTools._FloatView) {
  83690. DDSTools._FloatView = new Float32Array(1);
  83691. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83692. }
  83693. DDSTools._FloatView[0] = value;
  83694. var x = DDSTools._Int32View[0];
  83695. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83696. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83697. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83698. /* If zero, or denormal, or exponent underflows too much for a denormal
  83699. * half, return signed zero. */
  83700. if (e < 103) {
  83701. return bits;
  83702. }
  83703. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83704. if (e > 142) {
  83705. bits |= 0x7c00;
  83706. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83707. * not Inf, so make sure we set one mantissa bit too. */
  83708. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83709. return bits;
  83710. }
  83711. /* If exponent underflows but not too much, return a denormal */
  83712. if (e < 113) {
  83713. m |= 0x0800;
  83714. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83715. * to 1, which is OK. */
  83716. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83717. return bits;
  83718. }
  83719. bits |= ((e - 112) << 10) | (m >> 1);
  83720. bits += m & 1;
  83721. return bits;
  83722. };
  83723. DDSTools._FromHalfFloat = function (value) {
  83724. var s = (value & 0x8000) >> 15;
  83725. var e = (value & 0x7C00) >> 10;
  83726. var f = value & 0x03FF;
  83727. if (e === 0) {
  83728. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83729. }
  83730. else if (e == 0x1F) {
  83731. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83732. }
  83733. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83734. };
  83735. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83736. var destArray = new Float32Array(dataLength);
  83737. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83738. var index = 0;
  83739. for (var y = 0; y < height; y++) {
  83740. for (var x = 0; x < width; x++) {
  83741. var srcPos = (x + y * width) * 4;
  83742. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83743. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83744. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83745. if (DDSTools.StoreLODInAlphaChannel) {
  83746. destArray[index + 3] = lod;
  83747. }
  83748. else {
  83749. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83750. }
  83751. index += 4;
  83752. }
  83753. }
  83754. return destArray;
  83755. };
  83756. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83757. if (DDSTools.StoreLODInAlphaChannel) {
  83758. var destArray = new Uint16Array(dataLength);
  83759. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83760. var index = 0;
  83761. for (var y = 0; y < height; y++) {
  83762. for (var x = 0; x < width; x++) {
  83763. var srcPos = (x + y * width) * 4;
  83764. destArray[index] = srcData[srcPos];
  83765. destArray[index + 1] = srcData[srcPos + 1];
  83766. destArray[index + 2] = srcData[srcPos + 2];
  83767. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83768. index += 4;
  83769. }
  83770. }
  83771. return destArray;
  83772. }
  83773. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83774. };
  83775. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83776. if (DDSTools.StoreLODInAlphaChannel) {
  83777. var destArray = new Float32Array(dataLength);
  83778. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83779. var index = 0;
  83780. for (var y = 0; y < height; y++) {
  83781. for (var x = 0; x < width; x++) {
  83782. var srcPos = (x + y * width) * 4;
  83783. destArray[index] = srcData[srcPos];
  83784. destArray[index + 1] = srcData[srcPos + 1];
  83785. destArray[index + 2] = srcData[srcPos + 2];
  83786. destArray[index + 3] = lod;
  83787. index += 4;
  83788. }
  83789. }
  83790. return destArray;
  83791. }
  83792. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83793. };
  83794. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83795. var destArray = new Uint8Array(dataLength);
  83796. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83797. var index = 0;
  83798. for (var y = 0; y < height; y++) {
  83799. for (var x = 0; x < width; x++) {
  83800. var srcPos = (x + y * width) * 4;
  83801. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83802. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83803. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83804. if (DDSTools.StoreLODInAlphaChannel) {
  83805. destArray[index + 3] = lod;
  83806. }
  83807. else {
  83808. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83809. }
  83810. index += 4;
  83811. }
  83812. }
  83813. return destArray;
  83814. };
  83815. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83816. var destArray = new Uint8Array(dataLength);
  83817. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83818. var index = 0;
  83819. for (var y = 0; y < height; y++) {
  83820. for (var x = 0; x < width; x++) {
  83821. var srcPos = (x + y * width) * 4;
  83822. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83823. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83824. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83825. if (DDSTools.StoreLODInAlphaChannel) {
  83826. destArray[index + 3] = lod;
  83827. }
  83828. else {
  83829. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83830. }
  83831. index += 4;
  83832. }
  83833. }
  83834. return destArray;
  83835. };
  83836. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83837. var byteArray = new Uint8Array(dataLength);
  83838. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83839. var index = 0;
  83840. for (var y = 0; y < height; y++) {
  83841. for (var x = 0; x < width; x++) {
  83842. var srcPos = (x + y * width) * 4;
  83843. byteArray[index] = srcData[srcPos + rOffset];
  83844. byteArray[index + 1] = srcData[srcPos + gOffset];
  83845. byteArray[index + 2] = srcData[srcPos + bOffset];
  83846. byteArray[index + 3] = srcData[srcPos + aOffset];
  83847. index += 4;
  83848. }
  83849. }
  83850. return byteArray;
  83851. };
  83852. DDSTools._ExtractLongWordOrder = function (value) {
  83853. if (value === 0 || value === 255 || value === -16777216) {
  83854. return 0;
  83855. }
  83856. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  83857. };
  83858. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  83859. var byteArray = new Uint8Array(dataLength);
  83860. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83861. var index = 0;
  83862. for (var y = 0; y < height; y++) {
  83863. for (var x = 0; x < width; x++) {
  83864. var srcPos = (x + y * width) * 3;
  83865. byteArray[index] = srcData[srcPos + rOffset];
  83866. byteArray[index + 1] = srcData[srcPos + gOffset];
  83867. byteArray[index + 2] = srcData[srcPos + bOffset];
  83868. index += 3;
  83869. }
  83870. }
  83871. return byteArray;
  83872. };
  83873. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  83874. var byteArray = new Uint8Array(dataLength);
  83875. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  83876. var index = 0;
  83877. for (var y = 0; y < height; y++) {
  83878. for (var x = 0; x < width; x++) {
  83879. var srcPos = (x + y * width);
  83880. byteArray[index] = srcData[srcPos];
  83881. index++;
  83882. }
  83883. }
  83884. return byteArray;
  83885. };
  83886. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  83887. if (lodIndex === void 0) { lodIndex = -1; }
  83888. var ext = engine.getCaps().s3tc;
  83889. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83890. var fourCC, width, height, dataLength = 0, dataOffset;
  83891. var byteArray, mipmapCount, mip;
  83892. var internalFormat = 0;
  83893. var format = 0;
  83894. var blockBytes = 1;
  83895. if (header[off_magic] !== DDS_MAGIC) {
  83896. BABYLON.Tools.Error("Invalid magic number in DDS header");
  83897. return;
  83898. }
  83899. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  83900. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  83901. return;
  83902. }
  83903. if (info.isCompressed && !ext) {
  83904. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  83905. return;
  83906. }
  83907. var bpp = header[off_RGBbpp];
  83908. dataOffset = header[off_size] + 4;
  83909. var computeFormats = false;
  83910. if (info.isFourCC) {
  83911. fourCC = header[off_pfFourCC];
  83912. switch (fourCC) {
  83913. case FOURCC_DXT1:
  83914. blockBytes = 8;
  83915. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  83916. break;
  83917. case FOURCC_DXT3:
  83918. blockBytes = 16;
  83919. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  83920. break;
  83921. case FOURCC_DXT5:
  83922. blockBytes = 16;
  83923. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  83924. break;
  83925. case FOURCC_D3DFMT_R16G16B16A16F:
  83926. computeFormats = true;
  83927. break;
  83928. case FOURCC_D3DFMT_R32G32B32A32F:
  83929. computeFormats = true;
  83930. break;
  83931. case FOURCC_DX10:
  83932. // There is an additionnal header so dataOffset need to be changed
  83933. dataOffset += 5 * 4; // 5 uints
  83934. var supported = false;
  83935. switch (info.dxgiFormat) {
  83936. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  83937. computeFormats = true;
  83938. supported = true;
  83939. break;
  83940. case DXGI_FORMAT_B8G8R8X8_UNORM:
  83941. info.isRGB = true;
  83942. info.isFourCC = false;
  83943. bpp = 32;
  83944. supported = true;
  83945. break;
  83946. }
  83947. if (supported) {
  83948. break;
  83949. }
  83950. default:
  83951. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  83952. return;
  83953. }
  83954. }
  83955. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  83956. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  83957. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  83958. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  83959. if (computeFormats) {
  83960. format = engine._getWebGLTextureType(info.textureType);
  83961. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83962. }
  83963. mipmapCount = 1;
  83964. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  83965. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83966. }
  83967. for (var face = 0; face < faces; face++) {
  83968. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  83969. width = header[off_width];
  83970. height = header[off_height];
  83971. for (mip = 0; mip < mipmapCount; ++mip) {
  83972. if (lodIndex === -1 || lodIndex === mip) {
  83973. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  83974. var i = (lodIndex === -1) ? mip : 0;
  83975. if (!info.isCompressed && info.isFourCC) {
  83976. dataLength = width * height * 4;
  83977. var floatArray = null;
  83978. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  83979. if (bpp === 128) {
  83980. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83981. }
  83982. else if (bpp === 64) {
  83983. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83984. }
  83985. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83986. format = engine._getWebGLTextureType(info.textureType);
  83987. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83988. }
  83989. else {
  83990. if (bpp === 128) {
  83991. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83992. }
  83993. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  83994. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  83995. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83996. format = engine._getWebGLTextureType(info.textureType);
  83997. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  83998. }
  83999. else { // 64
  84000. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84001. }
  84002. }
  84003. if (floatArray) {
  84004. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84005. }
  84006. }
  84007. else if (info.isRGB) {
  84008. if (bpp === 24) {
  84009. dataLength = width * height * 3;
  84010. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84011. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84012. }
  84013. else { // 32
  84014. dataLength = width * height * 4;
  84015. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84016. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84017. }
  84018. }
  84019. else if (info.isLuminance) {
  84020. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84021. var unpaddedRowSize = width;
  84022. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84023. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84024. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84025. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84026. }
  84027. else {
  84028. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84029. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84030. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84031. }
  84032. }
  84033. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84034. width *= 0.5;
  84035. height *= 0.5;
  84036. width = Math.max(1.0, width);
  84037. height = Math.max(1.0, height);
  84038. }
  84039. if (currentFace !== undefined) {
  84040. // Loading a single face
  84041. break;
  84042. }
  84043. }
  84044. };
  84045. DDSTools.StoreLODInAlphaChannel = false;
  84046. return DDSTools;
  84047. }());
  84048. BABYLON.DDSTools = DDSTools;
  84049. })(BABYLON || (BABYLON = {}));
  84050. //# sourceMappingURL=babylon.dds.js.map
  84051. var BABYLON;
  84052. (function (BABYLON) {
  84053. /**
  84054. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84055. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84056. */
  84057. var KhronosTextureContainer = /** @class */ (function () {
  84058. /**
  84059. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84060. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84061. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84062. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84063. */
  84064. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84065. this.arrayBuffer = arrayBuffer;
  84066. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84067. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84068. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84069. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84070. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84071. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84072. BABYLON.Tools.Error("texture missing KTX identifier");
  84073. return;
  84074. }
  84075. // load the reset of the header in native 32 bit int
  84076. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84077. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84078. var oppositeEndianess = header[0] === 0x01020304;
  84079. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84080. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84081. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84082. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84083. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84084. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84085. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84086. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84087. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84088. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84089. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84090. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84091. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84092. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84093. if (this.glType !== 0) {
  84094. BABYLON.Tools.Error("only compressed formats currently supported");
  84095. return;
  84096. }
  84097. else {
  84098. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84099. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84100. }
  84101. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84102. BABYLON.Tools.Error("only 2D textures currently supported");
  84103. return;
  84104. }
  84105. if (this.numberOfArrayElements !== 0) {
  84106. BABYLON.Tools.Error("texture arrays not currently supported");
  84107. return;
  84108. }
  84109. if (this.numberOfFaces !== facesExpected) {
  84110. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84111. return;
  84112. }
  84113. // we now have a completely validated file, so could use existence of loadType as success
  84114. // would need to make this more elaborate & adjust checks above to support more than one load type
  84115. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84116. }
  84117. // not as fast hardware based, but will probably never need to use
  84118. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84119. return ((val & 0xFF) << 24)
  84120. | ((val & 0xFF00) << 8)
  84121. | ((val >> 8) & 0xFF00)
  84122. | ((val >> 24) & 0xFF);
  84123. };
  84124. /**
  84125. * It is assumed that the texture has already been created & is currently bound
  84126. */
  84127. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84128. switch (this.loadType) {
  84129. case KhronosTextureContainer.COMPRESSED_2D:
  84130. this._upload2DCompressedLevels(gl, loadMipmaps);
  84131. break;
  84132. case KhronosTextureContainer.TEX_2D:
  84133. case KhronosTextureContainer.COMPRESSED_3D:
  84134. case KhronosTextureContainer.TEX_3D:
  84135. }
  84136. };
  84137. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84138. // initialize width & height for level 1
  84139. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84140. var width = this.pixelWidth;
  84141. var height = this.pixelHeight;
  84142. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84143. for (var level = 0; level < mipmapCount; level++) {
  84144. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84145. for (var face = 0; face < this.numberOfFaces; face++) {
  84146. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84147. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84148. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84149. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84150. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84151. }
  84152. width = Math.max(1.0, width * 0.5);
  84153. height = Math.max(1.0, height * 0.5);
  84154. }
  84155. };
  84156. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84157. // load types
  84158. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84159. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84160. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84161. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84162. return KhronosTextureContainer;
  84163. }());
  84164. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84165. })(BABYLON || (BABYLON = {}));
  84166. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84167. var BABYLON;
  84168. (function (BABYLON) {
  84169. var Debug;
  84170. (function (Debug) {
  84171. /**
  84172. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84173. */
  84174. var SkeletonViewer = /** @class */ (function () {
  84175. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84176. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84177. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84178. this.skeleton = skeleton;
  84179. this.mesh = mesh;
  84180. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84181. this.renderingGroupId = renderingGroupId;
  84182. this.color = BABYLON.Color3.White();
  84183. this._debugLines = new Array();
  84184. this._isEnabled = false;
  84185. this._scene = scene;
  84186. this.update();
  84187. this._renderFunction = this.update.bind(this);
  84188. }
  84189. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84190. get: function () {
  84191. return this._isEnabled;
  84192. },
  84193. set: function (value) {
  84194. if (this._isEnabled === value) {
  84195. return;
  84196. }
  84197. this._isEnabled = value;
  84198. if (value) {
  84199. this._scene.registerBeforeRender(this._renderFunction);
  84200. }
  84201. else {
  84202. this._scene.unregisterBeforeRender(this._renderFunction);
  84203. }
  84204. },
  84205. enumerable: true,
  84206. configurable: true
  84207. });
  84208. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84209. if (x === void 0) { x = 0; }
  84210. if (y === void 0) { y = 0; }
  84211. if (z === void 0) { z = 0; }
  84212. var tmat = BABYLON.Tmp.Matrix[0];
  84213. var parentBone = bone.getParent();
  84214. tmat.copyFrom(bone.getLocalMatrix());
  84215. if (x !== 0 || y !== 0 || z !== 0) {
  84216. var tmat2 = BABYLON.Tmp.Matrix[1];
  84217. BABYLON.Matrix.IdentityToRef(tmat2);
  84218. tmat2.m[12] = x;
  84219. tmat2.m[13] = y;
  84220. tmat2.m[14] = z;
  84221. tmat2.multiplyToRef(tmat, tmat);
  84222. }
  84223. if (parentBone) {
  84224. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84225. }
  84226. tmat.multiplyToRef(meshMat, tmat);
  84227. position.x = tmat.m[12];
  84228. position.y = tmat.m[13];
  84229. position.z = tmat.m[14];
  84230. };
  84231. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84232. var len = bones.length;
  84233. var meshPos = this.mesh.position;
  84234. for (var i = 0; i < len; i++) {
  84235. var bone = bones[i];
  84236. var points = this._debugLines[i];
  84237. if (!points) {
  84238. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84239. this._debugLines[i] = points;
  84240. }
  84241. this._getBonePosition(points[0], bone, meshMat);
  84242. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84243. points[0].subtractInPlace(meshPos);
  84244. points[1].subtractInPlace(meshPos);
  84245. }
  84246. };
  84247. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84248. var len = bones.length;
  84249. var boneNum = 0;
  84250. var meshPos = this.mesh.position;
  84251. for (var i = len - 1; i >= 0; i--) {
  84252. var childBone = bones[i];
  84253. var parentBone = childBone.getParent();
  84254. if (!parentBone) {
  84255. continue;
  84256. }
  84257. var points = this._debugLines[boneNum];
  84258. if (!points) {
  84259. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84260. this._debugLines[boneNum] = points;
  84261. }
  84262. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84263. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84264. points[0].subtractInPlace(meshPos);
  84265. points[1].subtractInPlace(meshPos);
  84266. boneNum++;
  84267. }
  84268. };
  84269. SkeletonViewer.prototype.update = function () {
  84270. if (this.autoUpdateBonesMatrices) {
  84271. this.skeleton.computeAbsoluteTransforms();
  84272. }
  84273. if (this.skeleton.bones[0].length === undefined) {
  84274. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84275. }
  84276. else {
  84277. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84278. }
  84279. if (!this._debugMesh) {
  84280. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84281. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84282. }
  84283. else {
  84284. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84285. }
  84286. this._debugMesh.position.copyFrom(this.mesh.position);
  84287. this._debugMesh.color = this.color;
  84288. };
  84289. SkeletonViewer.prototype.dispose = function () {
  84290. if (this._debugMesh) {
  84291. this.isEnabled = false;
  84292. this._debugMesh.dispose();
  84293. this._debugMesh = null;
  84294. }
  84295. };
  84296. return SkeletonViewer;
  84297. }());
  84298. Debug.SkeletonViewer = SkeletonViewer;
  84299. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84300. })(BABYLON || (BABYLON = {}));
  84301. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84302. /**
  84303. * Module Debug contains the (visual) components to debug a scene correctly
  84304. */
  84305. var BABYLON;
  84306. (function (BABYLON) {
  84307. var Debug;
  84308. (function (Debug) {
  84309. /**
  84310. * The Axes viewer will show 3 axes in a specific point in space
  84311. */
  84312. var AxesViewer = /** @class */ (function () {
  84313. function AxesViewer(scene, scaleLines) {
  84314. if (scaleLines === void 0) { scaleLines = 1; }
  84315. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84316. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84317. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84318. this.scaleLines = 1;
  84319. this.scaleLines = scaleLines;
  84320. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84321. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84322. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84323. this._xmesh.renderingGroupId = 2;
  84324. this._ymesh.renderingGroupId = 2;
  84325. this._zmesh.renderingGroupId = 2;
  84326. this._xmesh.material.checkReadyOnlyOnce = true;
  84327. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84328. this._ymesh.material.checkReadyOnlyOnce = true;
  84329. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84330. this._zmesh.material.checkReadyOnlyOnce = true;
  84331. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84332. this.scene = scene;
  84333. }
  84334. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84335. var scaleLines = this.scaleLines;
  84336. if (this._xmesh) {
  84337. this._xmesh.position.copyFrom(position);
  84338. }
  84339. if (this._ymesh) {
  84340. this._ymesh.position.copyFrom(position);
  84341. }
  84342. if (this._zmesh) {
  84343. this._zmesh.position.copyFrom(position);
  84344. }
  84345. var point2 = this._xline[1];
  84346. point2.x = xaxis.x * scaleLines;
  84347. point2.y = xaxis.y * scaleLines;
  84348. point2.z = xaxis.z * scaleLines;
  84349. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84350. point2 = this._yline[1];
  84351. point2.x = yaxis.x * scaleLines;
  84352. point2.y = yaxis.y * scaleLines;
  84353. point2.z = yaxis.z * scaleLines;
  84354. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84355. point2 = this._zline[1];
  84356. point2.x = zaxis.x * scaleLines;
  84357. point2.y = zaxis.y * scaleLines;
  84358. point2.z = zaxis.z * scaleLines;
  84359. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84360. };
  84361. AxesViewer.prototype.dispose = function () {
  84362. if (this._xmesh) {
  84363. this._xmesh.dispose();
  84364. }
  84365. if (this._ymesh) {
  84366. this._ymesh.dispose();
  84367. }
  84368. if (this._zmesh) {
  84369. this._zmesh.dispose();
  84370. }
  84371. this._xmesh = null;
  84372. this._ymesh = null;
  84373. this._zmesh = null;
  84374. this.scene = null;
  84375. };
  84376. return AxesViewer;
  84377. }());
  84378. Debug.AxesViewer = AxesViewer;
  84379. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84380. })(BABYLON || (BABYLON = {}));
  84381. //# sourceMappingURL=babylon.axesViewer.js.map
  84382. var BABYLON;
  84383. (function (BABYLON) {
  84384. var Debug;
  84385. (function (Debug) {
  84386. /**
  84387. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84388. */
  84389. var BoneAxesViewer = /** @class */ (function (_super) {
  84390. __extends(BoneAxesViewer, _super);
  84391. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84392. if (scaleLines === void 0) { scaleLines = 1; }
  84393. var _this = _super.call(this, scene, scaleLines) || this;
  84394. _this.pos = BABYLON.Vector3.Zero();
  84395. _this.xaxis = BABYLON.Vector3.Zero();
  84396. _this.yaxis = BABYLON.Vector3.Zero();
  84397. _this.zaxis = BABYLON.Vector3.Zero();
  84398. _this.mesh = mesh;
  84399. _this.bone = bone;
  84400. return _this;
  84401. }
  84402. BoneAxesViewer.prototype.update = function () {
  84403. if (!this.mesh || !this.bone) {
  84404. return;
  84405. }
  84406. var bone = this.bone;
  84407. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84408. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84409. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84410. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84411. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84412. };
  84413. BoneAxesViewer.prototype.dispose = function () {
  84414. if (this.mesh) {
  84415. this.mesh = null;
  84416. this.bone = null;
  84417. _super.prototype.dispose.call(this);
  84418. }
  84419. };
  84420. return BoneAxesViewer;
  84421. }(Debug.AxesViewer));
  84422. Debug.BoneAxesViewer = BoneAxesViewer;
  84423. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84424. })(BABYLON || (BABYLON = {}));
  84425. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84426. var BABYLON;
  84427. (function (BABYLON) {
  84428. var RayHelper = /** @class */ (function () {
  84429. function RayHelper(ray) {
  84430. this.ray = ray;
  84431. }
  84432. RayHelper.CreateAndShow = function (ray, scene, color) {
  84433. var helper = new RayHelper(ray);
  84434. helper.show(scene, color);
  84435. return helper;
  84436. };
  84437. RayHelper.prototype.show = function (scene, color) {
  84438. if (!this._renderFunction && this.ray) {
  84439. var ray = this.ray;
  84440. this._renderFunction = this._render.bind(this);
  84441. this._scene = scene;
  84442. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84443. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84444. if (this._renderFunction) {
  84445. this._scene.registerBeforeRender(this._renderFunction);
  84446. }
  84447. }
  84448. if (color && this._renderLine) {
  84449. this._renderLine.color.copyFrom(color);
  84450. }
  84451. };
  84452. RayHelper.prototype.hide = function () {
  84453. if (this._renderFunction && this._scene) {
  84454. this._scene.unregisterBeforeRender(this._renderFunction);
  84455. this._scene = null;
  84456. this._renderFunction = null;
  84457. if (this._renderLine) {
  84458. this._renderLine.dispose();
  84459. this._renderLine = null;
  84460. }
  84461. this._renderPoints = [];
  84462. }
  84463. };
  84464. RayHelper.prototype._render = function () {
  84465. var ray = this.ray;
  84466. if (!ray) {
  84467. return;
  84468. }
  84469. var point = this._renderPoints[1];
  84470. var len = Math.min(ray.length, 1000000);
  84471. point.copyFrom(ray.direction);
  84472. point.scaleInPlace(len);
  84473. point.addInPlace(ray.origin);
  84474. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84475. };
  84476. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84477. this._attachedToMesh = mesh;
  84478. var ray = this.ray;
  84479. if (!ray) {
  84480. return;
  84481. }
  84482. if (!ray.direction) {
  84483. ray.direction = BABYLON.Vector3.Zero();
  84484. }
  84485. if (!ray.origin) {
  84486. ray.origin = BABYLON.Vector3.Zero();
  84487. }
  84488. if (length) {
  84489. ray.length = length;
  84490. }
  84491. if (!meshSpaceOrigin) {
  84492. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84493. }
  84494. if (!meshSpaceDirection) {
  84495. // -1 so that this will work with Mesh.lookAt
  84496. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84497. }
  84498. if (!this._meshSpaceDirection) {
  84499. this._meshSpaceDirection = meshSpaceDirection.clone();
  84500. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84501. }
  84502. else {
  84503. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84504. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84505. }
  84506. if (!this._updateToMeshFunction) {
  84507. this._updateToMeshFunction = this._updateToMesh.bind(this);
  84508. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  84509. }
  84510. this._updateToMesh();
  84511. };
  84512. RayHelper.prototype.detachFromMesh = function () {
  84513. if (this._attachedToMesh) {
  84514. if (this._updateToMeshFunction) {
  84515. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  84516. }
  84517. this._attachedToMesh = null;
  84518. this._updateToMeshFunction = null;
  84519. }
  84520. };
  84521. RayHelper.prototype._updateToMesh = function () {
  84522. var ray = this.ray;
  84523. if (!this._attachedToMesh || !ray) {
  84524. return;
  84525. }
  84526. if (this._attachedToMesh._isDisposed) {
  84527. this.detachFromMesh();
  84528. return;
  84529. }
  84530. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  84531. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  84532. };
  84533. RayHelper.prototype.dispose = function () {
  84534. this.hide();
  84535. this.detachFromMesh();
  84536. this.ray = null;
  84537. };
  84538. return RayHelper;
  84539. }());
  84540. BABYLON.RayHelper = RayHelper;
  84541. })(BABYLON || (BABYLON = {}));
  84542. //# sourceMappingURL=babylon.rayHelper.js.map
  84543. var BABYLON;
  84544. (function (BABYLON) {
  84545. // load the inspector using require, if not present in the global namespace.
  84546. var DebugLayer = /** @class */ (function () {
  84547. function DebugLayer(scene) {
  84548. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84549. this._scene = scene;
  84550. // load inspector using require, if it doesn't exist on the global namespace.
  84551. }
  84552. /** Creates the inspector window. */
  84553. DebugLayer.prototype._createInspector = function (config) {
  84554. if (config === void 0) { config = {}; }
  84555. var popup = config.popup || false;
  84556. var initialTab = config.initialTab || 0;
  84557. var parentElement = config.parentElement || null;
  84558. if (!this._inspector) {
  84559. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84560. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  84561. } // else nothing to do,; instance is already existing
  84562. };
  84563. DebugLayer.prototype.isVisible = function () {
  84564. if (!this._inspector) {
  84565. return false;
  84566. }
  84567. return true;
  84568. };
  84569. DebugLayer.prototype.hide = function () {
  84570. if (this._inspector) {
  84571. try {
  84572. this._inspector.dispose();
  84573. }
  84574. catch (e) {
  84575. // If the inspector has been removed directly from the inspector tool
  84576. }
  84577. this._inspector = null;
  84578. }
  84579. };
  84580. DebugLayer.prototype.show = function (config) {
  84581. if (config === void 0) { config = {}; }
  84582. if (typeof this.BJSINSPECTOR == 'undefined') {
  84583. // Load inspector and add it to the DOM
  84584. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84585. }
  84586. else {
  84587. // Otherwise creates the inspector
  84588. this._createInspector(config);
  84589. }
  84590. };
  84591. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84592. return DebugLayer;
  84593. }());
  84594. BABYLON.DebugLayer = DebugLayer;
  84595. })(BABYLON || (BABYLON = {}));
  84596. //# sourceMappingURL=babylon.debugLayer.js.map
  84597. var BABYLON;
  84598. (function (BABYLON) {
  84599. var Debug;
  84600. (function (Debug) {
  84601. /**
  84602. * Used to show the physics impostor around the specific mesh.
  84603. */
  84604. var PhysicsViewer = /** @class */ (function () {
  84605. function PhysicsViewer(scene) {
  84606. this._impostors = [];
  84607. this._meshes = [];
  84608. this._numMeshes = 0;
  84609. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84610. var physicEngine = this._scene.getPhysicsEngine();
  84611. if (physicEngine) {
  84612. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84613. }
  84614. }
  84615. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84616. var plugin = this._physicsEnginePlugin;
  84617. for (var i = 0; i < this._numMeshes; i++) {
  84618. var impostor = this._impostors[i];
  84619. if (!impostor) {
  84620. continue;
  84621. }
  84622. if (impostor.isDisposed) {
  84623. this.hideImpostor(this._impostors[i--]);
  84624. }
  84625. else {
  84626. var mesh = this._meshes[i];
  84627. if (mesh && plugin) {
  84628. plugin.syncMeshWithImpostor(mesh, impostor);
  84629. }
  84630. }
  84631. }
  84632. };
  84633. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84634. if (!this._scene) {
  84635. return;
  84636. }
  84637. for (var i = 0; i < this._numMeshes; i++) {
  84638. if (this._impostors[i] == impostor) {
  84639. return;
  84640. }
  84641. }
  84642. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84643. if (debugMesh) {
  84644. this._impostors[this._numMeshes] = impostor;
  84645. this._meshes[this._numMeshes] = debugMesh;
  84646. if (this._numMeshes === 0) {
  84647. this._renderFunction = this._updateDebugMeshes.bind(this);
  84648. this._scene.registerBeforeRender(this._renderFunction);
  84649. }
  84650. this._numMeshes++;
  84651. }
  84652. };
  84653. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84654. if (!impostor || !this._scene) {
  84655. return;
  84656. }
  84657. var removed = false;
  84658. for (var i = 0; i < this._numMeshes; i++) {
  84659. if (this._impostors[i] == impostor) {
  84660. var mesh = this._meshes[i];
  84661. if (!mesh) {
  84662. continue;
  84663. }
  84664. this._scene.removeMesh(mesh);
  84665. mesh.dispose();
  84666. this._numMeshes--;
  84667. if (this._numMeshes > 0) {
  84668. this._meshes[i] = this._meshes[this._numMeshes];
  84669. this._impostors[i] = this._impostors[this._numMeshes];
  84670. this._meshes[this._numMeshes] = null;
  84671. this._impostors[this._numMeshes] = null;
  84672. }
  84673. else {
  84674. this._meshes[0] = null;
  84675. this._impostors[0] = null;
  84676. }
  84677. removed = true;
  84678. break;
  84679. }
  84680. }
  84681. if (removed && this._numMeshes === 0) {
  84682. this._scene.unregisterBeforeRender(this._renderFunction);
  84683. }
  84684. };
  84685. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84686. if (!this._debugMaterial) {
  84687. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84688. this._debugMaterial.wireframe = true;
  84689. }
  84690. return this._debugMaterial;
  84691. };
  84692. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84693. if (!this._debugBoxMesh) {
  84694. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84695. this._debugBoxMesh.renderingGroupId = 1;
  84696. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84697. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84698. scene.removeMesh(this._debugBoxMesh);
  84699. }
  84700. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84701. };
  84702. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84703. if (!this._debugSphereMesh) {
  84704. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84705. this._debugSphereMesh.renderingGroupId = 1;
  84706. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84707. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84708. scene.removeMesh(this._debugSphereMesh);
  84709. }
  84710. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84711. };
  84712. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84713. var mesh = null;
  84714. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84715. mesh = this._getDebugBoxMesh(scene);
  84716. impostor.getBoxSizeToRef(mesh.scaling);
  84717. }
  84718. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84719. mesh = this._getDebugSphereMesh(scene);
  84720. var radius = impostor.getRadius();
  84721. mesh.scaling.x = radius * 2;
  84722. mesh.scaling.y = radius * 2;
  84723. mesh.scaling.z = radius * 2;
  84724. }
  84725. return mesh;
  84726. };
  84727. PhysicsViewer.prototype.dispose = function () {
  84728. for (var i = 0; i < this._numMeshes; i++) {
  84729. this.hideImpostor(this._impostors[i]);
  84730. }
  84731. if (this._debugBoxMesh) {
  84732. this._debugBoxMesh.dispose();
  84733. }
  84734. if (this._debugSphereMesh) {
  84735. this._debugSphereMesh.dispose();
  84736. }
  84737. if (this._debugMaterial) {
  84738. this._debugMaterial.dispose();
  84739. }
  84740. this._impostors.length = 0;
  84741. this._scene = null;
  84742. this._physicsEnginePlugin = null;
  84743. };
  84744. return PhysicsViewer;
  84745. }());
  84746. Debug.PhysicsViewer = PhysicsViewer;
  84747. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84748. })(BABYLON || (BABYLON = {}));
  84749. //# sourceMappingURL=babylon.physicsViewer.js.map
  84750. var BABYLON;
  84751. (function (BABYLON) {
  84752. var BoundingBoxRenderer = /** @class */ (function () {
  84753. function BoundingBoxRenderer(scene) {
  84754. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84755. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84756. this.showBackLines = true;
  84757. this.renderList = new BABYLON.SmartArray(32);
  84758. this._vertexBuffers = {};
  84759. this._scene = scene;
  84760. }
  84761. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84762. if (this._colorShader) {
  84763. return;
  84764. }
  84765. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84766. attributes: [BABYLON.VertexBuffer.PositionKind],
  84767. uniforms: ["world", "viewProjection", "color"]
  84768. });
  84769. var engine = this._scene.getEngine();
  84770. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84771. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84772. this._createIndexBuffer();
  84773. };
  84774. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84775. var engine = this._scene.getEngine();
  84776. 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]);
  84777. };
  84778. BoundingBoxRenderer.prototype._rebuild = function () {
  84779. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84780. if (vb) {
  84781. vb._rebuild();
  84782. }
  84783. this._createIndexBuffer();
  84784. };
  84785. BoundingBoxRenderer.prototype.reset = function () {
  84786. this.renderList.reset();
  84787. };
  84788. BoundingBoxRenderer.prototype.render = function () {
  84789. if (this.renderList.length === 0) {
  84790. return;
  84791. }
  84792. this._prepareRessources();
  84793. if (!this._colorShader.isReady()) {
  84794. return;
  84795. }
  84796. var engine = this._scene.getEngine();
  84797. engine.setDepthWrite(false);
  84798. this._colorShader._preBind();
  84799. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84800. var boundingBox = this.renderList.data[boundingBoxIndex];
  84801. var min = boundingBox.minimum;
  84802. var max = boundingBox.maximum;
  84803. var diff = max.subtract(min);
  84804. var median = min.add(diff.scale(0.5));
  84805. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84806. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84807. .multiply(boundingBox.getWorldMatrix());
  84808. // VBOs
  84809. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84810. if (this.showBackLines) {
  84811. // Back
  84812. engine.setDepthFunctionToGreaterOrEqual();
  84813. this._scene.resetCachedMaterial();
  84814. this._colorShader.setColor4("color", this.backColor.toColor4());
  84815. this._colorShader.bind(worldMatrix);
  84816. // Draw order
  84817. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84818. }
  84819. // Front
  84820. engine.setDepthFunctionToLess();
  84821. this._scene.resetCachedMaterial();
  84822. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84823. this._colorShader.bind(worldMatrix);
  84824. // Draw order
  84825. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84826. }
  84827. this._colorShader.unbind();
  84828. engine.setDepthFunctionToLessOrEqual();
  84829. engine.setDepthWrite(true);
  84830. };
  84831. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84832. this._prepareRessources();
  84833. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84834. return;
  84835. }
  84836. var engine = this._scene.getEngine();
  84837. engine.setDepthWrite(false);
  84838. engine.setColorWrite(false);
  84839. this._colorShader._preBind();
  84840. var boundingBox = mesh._boundingInfo.boundingBox;
  84841. var min = boundingBox.minimum;
  84842. var max = boundingBox.maximum;
  84843. var diff = max.subtract(min);
  84844. var median = min.add(diff.scale(0.5));
  84845. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84846. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84847. .multiply(boundingBox.getWorldMatrix());
  84848. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84849. engine.setDepthFunctionToLess();
  84850. this._scene.resetCachedMaterial();
  84851. this._colorShader.bind(worldMatrix);
  84852. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84853. this._colorShader.unbind();
  84854. engine.setDepthFunctionToLessOrEqual();
  84855. engine.setDepthWrite(true);
  84856. engine.setColorWrite(true);
  84857. };
  84858. BoundingBoxRenderer.prototype.dispose = function () {
  84859. if (!this._colorShader) {
  84860. return;
  84861. }
  84862. this.renderList.dispose();
  84863. this._colorShader.dispose();
  84864. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84865. if (buffer) {
  84866. buffer.dispose();
  84867. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84868. }
  84869. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84870. };
  84871. return BoundingBoxRenderer;
  84872. }());
  84873. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  84874. })(BABYLON || (BABYLON = {}));
  84875. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  84876. var BABYLON;
  84877. (function (BABYLON) {
  84878. /**
  84879. * Defines a target to use with MorphTargetManager
  84880. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  84881. */
  84882. var MorphTarget = /** @class */ (function () {
  84883. /**
  84884. * Creates a new MorphTarget
  84885. * @param name defines the name of the target
  84886. * @param influence defines the influence to use
  84887. */
  84888. function MorphTarget(
  84889. /** defines the name of the target */
  84890. name, influence) {
  84891. if (influence === void 0) { influence = 0; }
  84892. this.name = name;
  84893. /**
  84894. * Gets or sets the list of animations
  84895. */
  84896. this.animations = new Array();
  84897. this._positions = null;
  84898. this._normals = null;
  84899. this._tangents = null;
  84900. /**
  84901. * Observable raised when the influence changes
  84902. */
  84903. this.onInfluenceChanged = new BABYLON.Observable();
  84904. this.influence = influence;
  84905. }
  84906. Object.defineProperty(MorphTarget.prototype, "influence", {
  84907. /**
  84908. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  84909. */
  84910. get: function () {
  84911. return this._influence;
  84912. },
  84913. set: function (influence) {
  84914. if (this._influence === influence) {
  84915. return;
  84916. }
  84917. var previous = this._influence;
  84918. this._influence = influence;
  84919. if (this.onInfluenceChanged.hasObservers) {
  84920. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  84921. }
  84922. },
  84923. enumerable: true,
  84924. configurable: true
  84925. });
  84926. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  84927. /**
  84928. * Gets a boolean defining if the target contains position data
  84929. */
  84930. get: function () {
  84931. return !!this._positions;
  84932. },
  84933. enumerable: true,
  84934. configurable: true
  84935. });
  84936. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  84937. /**
  84938. * Gets a boolean defining if the target contains normal data
  84939. */
  84940. get: function () {
  84941. return !!this._normals;
  84942. },
  84943. enumerable: true,
  84944. configurable: true
  84945. });
  84946. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  84947. /**
  84948. * Gets a boolean defining if the target contains tangent data
  84949. */
  84950. get: function () {
  84951. return !!this._tangents;
  84952. },
  84953. enumerable: true,
  84954. configurable: true
  84955. });
  84956. /**
  84957. * Affects position data to this target
  84958. * @param data defines the position data to use
  84959. */
  84960. MorphTarget.prototype.setPositions = function (data) {
  84961. this._positions = data;
  84962. };
  84963. /**
  84964. * Gets the position data stored in this target
  84965. * @returns a FloatArray containing the position data (or null if not present)
  84966. */
  84967. MorphTarget.prototype.getPositions = function () {
  84968. return this._positions;
  84969. };
  84970. /**
  84971. * Affects normal data to this target
  84972. * @param data defines the normal data to use
  84973. */
  84974. MorphTarget.prototype.setNormals = function (data) {
  84975. this._normals = data;
  84976. };
  84977. /**
  84978. * Gets the normal data stored in this target
  84979. * @returns a FloatArray containing the normal data (or null if not present)
  84980. */
  84981. MorphTarget.prototype.getNormals = function () {
  84982. return this._normals;
  84983. };
  84984. /**
  84985. * Affects tangent data to this target
  84986. * @param data defines the tangent data to use
  84987. */
  84988. MorphTarget.prototype.setTangents = function (data) {
  84989. this._tangents = data;
  84990. };
  84991. /**
  84992. * Gets the tangent data stored in this target
  84993. * @returns a FloatArray containing the tangent data (or null if not present)
  84994. */
  84995. MorphTarget.prototype.getTangents = function () {
  84996. return this._tangents;
  84997. };
  84998. /**
  84999. * Serializes the current target into a Serialization object
  85000. * @returns the serialized object
  85001. */
  85002. MorphTarget.prototype.serialize = function () {
  85003. var serializationObject = {};
  85004. serializationObject.name = this.name;
  85005. serializationObject.influence = this.influence;
  85006. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85007. if (this.hasNormals) {
  85008. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85009. }
  85010. if (this.hasTangents) {
  85011. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85012. }
  85013. // Animations
  85014. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85015. return serializationObject;
  85016. };
  85017. // Statics
  85018. /**
  85019. * Creates a new target from serialized data
  85020. * @param serializationObject defines the serialized data to use
  85021. * @returns a new MorphTarget
  85022. */
  85023. MorphTarget.Parse = function (serializationObject) {
  85024. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85025. result.setPositions(serializationObject.positions);
  85026. if (serializationObject.normals) {
  85027. result.setNormals(serializationObject.normals);
  85028. }
  85029. if (serializationObject.tangents) {
  85030. result.setTangents(serializationObject.tangents);
  85031. }
  85032. // Animations
  85033. if (serializationObject.animations) {
  85034. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85035. var parsedAnimation = serializationObject.animations[animationIndex];
  85036. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85037. }
  85038. }
  85039. return result;
  85040. };
  85041. /**
  85042. * Creates a MorphTarget from mesh data
  85043. * @param mesh defines the source mesh
  85044. * @param name defines the name to use for the new target
  85045. * @param influence defines the influence to attach to the target
  85046. * @returns a new MorphTarget
  85047. */
  85048. MorphTarget.FromMesh = function (mesh, name, influence) {
  85049. if (!name) {
  85050. name = mesh.name;
  85051. }
  85052. var result = new MorphTarget(name, influence);
  85053. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85055. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85056. }
  85057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85058. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85059. }
  85060. return result;
  85061. };
  85062. return MorphTarget;
  85063. }());
  85064. BABYLON.MorphTarget = MorphTarget;
  85065. })(BABYLON || (BABYLON = {}));
  85066. //# sourceMappingURL=babylon.morphTarget.js.map
  85067. var BABYLON;
  85068. (function (BABYLON) {
  85069. /**
  85070. * This class is used to deform meshes using morphing between different targets
  85071. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85072. */
  85073. var MorphTargetManager = /** @class */ (function () {
  85074. /**
  85075. * Creates a new MorphTargetManager
  85076. * @param scene defines the current scene
  85077. */
  85078. function MorphTargetManager(scene) {
  85079. if (scene === void 0) { scene = null; }
  85080. this._targets = new Array();
  85081. this._targetObservable = new Array();
  85082. this._activeTargets = new BABYLON.SmartArray(16);
  85083. this._supportsNormals = false;
  85084. this._supportsTangents = false;
  85085. this._vertexCount = 0;
  85086. this._uniqueId = 0;
  85087. this._tempInfluences = new Array();
  85088. if (!scene) {
  85089. scene = BABYLON.Engine.LastCreatedScene;
  85090. }
  85091. this._scene = scene;
  85092. if (this._scene) {
  85093. this._scene.morphTargetManagers.push(this);
  85094. this._uniqueId = this._scene.getUniqueId();
  85095. }
  85096. }
  85097. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85098. /**
  85099. * Gets the unique ID of this manager
  85100. */
  85101. get: function () {
  85102. return this._uniqueId;
  85103. },
  85104. enumerable: true,
  85105. configurable: true
  85106. });
  85107. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85108. /**
  85109. * Gets the number of vertices handled by this manager
  85110. */
  85111. get: function () {
  85112. return this._vertexCount;
  85113. },
  85114. enumerable: true,
  85115. configurable: true
  85116. });
  85117. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85118. /**
  85119. * Gets a boolean indicating if this manager supports morphing of normals
  85120. */
  85121. get: function () {
  85122. return this._supportsNormals;
  85123. },
  85124. enumerable: true,
  85125. configurable: true
  85126. });
  85127. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85128. /**
  85129. * Gets a boolean indicating if this manager supports morphing of tangents
  85130. */
  85131. get: function () {
  85132. return this._supportsTangents;
  85133. },
  85134. enumerable: true,
  85135. configurable: true
  85136. });
  85137. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85138. /**
  85139. * Gets the number of targets stored in this manager
  85140. */
  85141. get: function () {
  85142. return this._targets.length;
  85143. },
  85144. enumerable: true,
  85145. configurable: true
  85146. });
  85147. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85148. /**
  85149. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85150. */
  85151. get: function () {
  85152. return this._activeTargets.length;
  85153. },
  85154. enumerable: true,
  85155. configurable: true
  85156. });
  85157. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85158. /**
  85159. * Gets the list of influences (one per target)
  85160. */
  85161. get: function () {
  85162. return this._influences;
  85163. },
  85164. enumerable: true,
  85165. configurable: true
  85166. });
  85167. /**
  85168. * Gets the active target at specified index. An active target is a target with an influence > 0
  85169. * @param index defines the index to check
  85170. * @returns the requested target
  85171. */
  85172. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85173. return this._activeTargets.data[index];
  85174. };
  85175. /**
  85176. * Gets the target at specified index
  85177. * @param index defines the index to check
  85178. * @returns the requested target
  85179. */
  85180. MorphTargetManager.prototype.getTarget = function (index) {
  85181. return this._targets[index];
  85182. };
  85183. /**
  85184. * Add a new target to this manager
  85185. * @param target defines the target to add
  85186. */
  85187. MorphTargetManager.prototype.addTarget = function (target) {
  85188. var _this = this;
  85189. this._targets.push(target);
  85190. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85191. _this._syncActiveTargets(needUpdate);
  85192. }));
  85193. this._syncActiveTargets(true);
  85194. };
  85195. /**
  85196. * Removes a target from the manager
  85197. * @param target defines the target to remove
  85198. */
  85199. MorphTargetManager.prototype.removeTarget = function (target) {
  85200. var index = this._targets.indexOf(target);
  85201. if (index >= 0) {
  85202. this._targets.splice(index, 1);
  85203. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85204. this._syncActiveTargets(true);
  85205. }
  85206. };
  85207. /**
  85208. * Serializes the current manager into a Serialization object
  85209. * @returns the serialized object
  85210. */
  85211. MorphTargetManager.prototype.serialize = function () {
  85212. var serializationObject = {};
  85213. serializationObject.id = this.uniqueId;
  85214. serializationObject.targets = [];
  85215. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85216. var target = _a[_i];
  85217. serializationObject.targets.push(target.serialize());
  85218. }
  85219. return serializationObject;
  85220. };
  85221. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85222. var influenceCount = 0;
  85223. this._activeTargets.reset();
  85224. this._supportsNormals = true;
  85225. this._supportsTangents = true;
  85226. this._vertexCount = 0;
  85227. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85228. var target = _a[_i];
  85229. this._activeTargets.push(target);
  85230. this._tempInfluences[influenceCount++] = target.influence;
  85231. var positions = target.getPositions();
  85232. if (positions) {
  85233. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85234. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85235. var vertexCount = positions.length / 3;
  85236. if (this._vertexCount === 0) {
  85237. this._vertexCount = vertexCount;
  85238. }
  85239. else if (this._vertexCount !== vertexCount) {
  85240. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85241. return;
  85242. }
  85243. }
  85244. }
  85245. if (!this._influences || this._influences.length !== influenceCount) {
  85246. this._influences = new Float32Array(influenceCount);
  85247. }
  85248. for (var index = 0; index < influenceCount; index++) {
  85249. this._influences[index] = this._tempInfluences[index];
  85250. }
  85251. if (needUpdate) {
  85252. this.synchronize();
  85253. }
  85254. };
  85255. /**
  85256. * Syncrhonize the targets with all the meshes using this morph target manager
  85257. */
  85258. MorphTargetManager.prototype.synchronize = function () {
  85259. if (!this._scene) {
  85260. return;
  85261. }
  85262. // Flag meshes as dirty to resync with the active targets
  85263. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85264. var mesh = _a[_i];
  85265. if (mesh.morphTargetManager === this) {
  85266. mesh._syncGeometryWithMorphTargetManager();
  85267. }
  85268. }
  85269. };
  85270. // Statics
  85271. /**
  85272. * Creates a new MorphTargetManager from serialized data
  85273. * @param serializationObject defines the serialized data
  85274. * @param scene defines the hosting scene
  85275. * @returns the new MorphTargetManager
  85276. */
  85277. MorphTargetManager.Parse = function (serializationObject, scene) {
  85278. var result = new MorphTargetManager(scene);
  85279. result._uniqueId = serializationObject.id;
  85280. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85281. var targetData = _a[_i];
  85282. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85283. }
  85284. return result;
  85285. };
  85286. return MorphTargetManager;
  85287. }());
  85288. BABYLON.MorphTargetManager = MorphTargetManager;
  85289. })(BABYLON || (BABYLON = {}));
  85290. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85291. var BABYLON;
  85292. (function (BABYLON) {
  85293. var Octree = /** @class */ (function () {
  85294. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85295. if (maxDepth === void 0) { maxDepth = 2; }
  85296. this.maxDepth = maxDepth;
  85297. this.dynamicContent = new Array();
  85298. this._maxBlockCapacity = maxBlockCapacity || 64;
  85299. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85300. this._creationFunc = creationFunc;
  85301. }
  85302. // Methods
  85303. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85304. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85305. };
  85306. Octree.prototype.addMesh = function (entry) {
  85307. for (var index = 0; index < this.blocks.length; index++) {
  85308. var block = this.blocks[index];
  85309. block.addEntry(entry);
  85310. }
  85311. };
  85312. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85313. this._selectionContent.reset();
  85314. for (var index = 0; index < this.blocks.length; index++) {
  85315. var block = this.blocks[index];
  85316. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85317. }
  85318. if (allowDuplicate) {
  85319. this._selectionContent.concat(this.dynamicContent);
  85320. }
  85321. else {
  85322. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85323. }
  85324. return this._selectionContent;
  85325. };
  85326. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85327. this._selectionContent.reset();
  85328. for (var index = 0; index < this.blocks.length; index++) {
  85329. var block = this.blocks[index];
  85330. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85331. }
  85332. if (allowDuplicate) {
  85333. this._selectionContent.concat(this.dynamicContent);
  85334. }
  85335. else {
  85336. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85337. }
  85338. return this._selectionContent;
  85339. };
  85340. Octree.prototype.intersectsRay = function (ray) {
  85341. this._selectionContent.reset();
  85342. for (var index = 0; index < this.blocks.length; index++) {
  85343. var block = this.blocks[index];
  85344. block.intersectsRay(ray, this._selectionContent);
  85345. }
  85346. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85347. return this._selectionContent;
  85348. };
  85349. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85350. target.blocks = new Array();
  85351. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85352. // Segmenting space
  85353. for (var x = 0; x < 2; x++) {
  85354. for (var y = 0; y < 2; y++) {
  85355. for (var z = 0; z < 2; z++) {
  85356. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85357. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85358. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85359. block.addEntries(entries);
  85360. target.blocks.push(block);
  85361. }
  85362. }
  85363. }
  85364. };
  85365. Octree.CreationFuncForMeshes = function (entry, block) {
  85366. var boundingInfo = entry.getBoundingInfo();
  85367. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85368. block.entries.push(entry);
  85369. }
  85370. };
  85371. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85372. var boundingInfo = entry.getBoundingInfo();
  85373. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85374. block.entries.push(entry);
  85375. }
  85376. };
  85377. return Octree;
  85378. }());
  85379. BABYLON.Octree = Octree;
  85380. })(BABYLON || (BABYLON = {}));
  85381. //# sourceMappingURL=babylon.octree.js.map
  85382. var BABYLON;
  85383. (function (BABYLON) {
  85384. var OctreeBlock = /** @class */ (function () {
  85385. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85386. this.entries = new Array();
  85387. this._boundingVectors = new Array();
  85388. this._capacity = capacity;
  85389. this._depth = depth;
  85390. this._maxDepth = maxDepth;
  85391. this._creationFunc = creationFunc;
  85392. this._minPoint = minPoint;
  85393. this._maxPoint = maxPoint;
  85394. this._boundingVectors.push(minPoint.clone());
  85395. this._boundingVectors.push(maxPoint.clone());
  85396. this._boundingVectors.push(minPoint.clone());
  85397. this._boundingVectors[2].x = maxPoint.x;
  85398. this._boundingVectors.push(minPoint.clone());
  85399. this._boundingVectors[3].y = maxPoint.y;
  85400. this._boundingVectors.push(minPoint.clone());
  85401. this._boundingVectors[4].z = maxPoint.z;
  85402. this._boundingVectors.push(maxPoint.clone());
  85403. this._boundingVectors[5].z = minPoint.z;
  85404. this._boundingVectors.push(maxPoint.clone());
  85405. this._boundingVectors[6].x = minPoint.x;
  85406. this._boundingVectors.push(maxPoint.clone());
  85407. this._boundingVectors[7].y = minPoint.y;
  85408. }
  85409. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85410. // Property
  85411. get: function () {
  85412. return this._capacity;
  85413. },
  85414. enumerable: true,
  85415. configurable: true
  85416. });
  85417. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85418. get: function () {
  85419. return this._minPoint;
  85420. },
  85421. enumerable: true,
  85422. configurable: true
  85423. });
  85424. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85425. get: function () {
  85426. return this._maxPoint;
  85427. },
  85428. enumerable: true,
  85429. configurable: true
  85430. });
  85431. // Methods
  85432. OctreeBlock.prototype.addEntry = function (entry) {
  85433. if (this.blocks) {
  85434. for (var index = 0; index < this.blocks.length; index++) {
  85435. var block = this.blocks[index];
  85436. block.addEntry(entry);
  85437. }
  85438. return;
  85439. }
  85440. this._creationFunc(entry, this);
  85441. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85442. this.createInnerBlocks();
  85443. }
  85444. };
  85445. OctreeBlock.prototype.addEntries = function (entries) {
  85446. for (var index = 0; index < entries.length; index++) {
  85447. var mesh = entries[index];
  85448. this.addEntry(mesh);
  85449. }
  85450. };
  85451. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85452. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85453. if (this.blocks) {
  85454. for (var index = 0; index < this.blocks.length; index++) {
  85455. var block = this.blocks[index];
  85456. block.select(frustumPlanes, selection, allowDuplicate);
  85457. }
  85458. return;
  85459. }
  85460. if (allowDuplicate) {
  85461. selection.concat(this.entries);
  85462. }
  85463. else {
  85464. selection.concatWithNoDuplicate(this.entries);
  85465. }
  85466. }
  85467. };
  85468. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85469. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85470. if (this.blocks) {
  85471. for (var index = 0; index < this.blocks.length; index++) {
  85472. var block = this.blocks[index];
  85473. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85474. }
  85475. return;
  85476. }
  85477. if (allowDuplicate) {
  85478. selection.concat(this.entries);
  85479. }
  85480. else {
  85481. selection.concatWithNoDuplicate(this.entries);
  85482. }
  85483. }
  85484. };
  85485. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85486. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85487. if (this.blocks) {
  85488. for (var index = 0; index < this.blocks.length; index++) {
  85489. var block = this.blocks[index];
  85490. block.intersectsRay(ray, selection);
  85491. }
  85492. return;
  85493. }
  85494. selection.concatWithNoDuplicate(this.entries);
  85495. }
  85496. };
  85497. OctreeBlock.prototype.createInnerBlocks = function () {
  85498. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85499. };
  85500. return OctreeBlock;
  85501. }());
  85502. BABYLON.OctreeBlock = OctreeBlock;
  85503. })(BABYLON || (BABYLON = {}));
  85504. //# sourceMappingURL=babylon.octreeBlock.js.map
  85505. var BABYLON;
  85506. (function (BABYLON) {
  85507. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  85508. __extends(VRDistortionCorrectionPostProcess, _super);
  85509. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  85510. var _this = _super.call(this, name, "vrDistortionCorrection", [
  85511. 'LensCenter',
  85512. 'Scale',
  85513. 'ScaleIn',
  85514. 'HmdWarpParam'
  85515. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  85516. _this._isRightEye = isRightEye;
  85517. _this._distortionFactors = vrMetrics.distortionK;
  85518. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  85519. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  85520. _this.adaptScaleToCurrentViewport = true;
  85521. _this.onSizeChangedObservable.add(function () {
  85522. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  85523. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  85524. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  85525. });
  85526. _this.onApplyObservable.add(function (effect) {
  85527. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  85528. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  85529. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  85530. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  85531. });
  85532. return _this;
  85533. }
  85534. return VRDistortionCorrectionPostProcess;
  85535. }(BABYLON.PostProcess));
  85536. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  85537. })(BABYLON || (BABYLON = {}));
  85538. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  85539. var BABYLON;
  85540. (function (BABYLON) {
  85541. var AnaglyphPostProcess = /** @class */ (function (_super) {
  85542. __extends(AnaglyphPostProcess, _super);
  85543. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  85544. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  85545. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85546. _this.onApplyObservable.add(function (effect) {
  85547. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  85548. });
  85549. return _this;
  85550. }
  85551. return AnaglyphPostProcess;
  85552. }(BABYLON.PostProcess));
  85553. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  85554. })(BABYLON || (BABYLON = {}));
  85555. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  85556. var BABYLON;
  85557. (function (BABYLON) {
  85558. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85559. __extends(StereoscopicInterlacePostProcess, _super);
  85560. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85561. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85562. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85563. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85564. _this.onSizeChangedObservable.add(function () {
  85565. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85566. });
  85567. _this.onApplyObservable.add(function (effect) {
  85568. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85569. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85570. });
  85571. return _this;
  85572. }
  85573. return StereoscopicInterlacePostProcess;
  85574. }(BABYLON.PostProcess));
  85575. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85576. })(BABYLON || (BABYLON = {}));
  85577. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85578. var BABYLON;
  85579. (function (BABYLON) {
  85580. /**
  85581. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85582. * Screen rotation is taken into account.
  85583. */
  85584. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85585. function FreeCameraDeviceOrientationInput() {
  85586. var _this = this;
  85587. this._screenOrientationAngle = 0;
  85588. this._screenQuaternion = new BABYLON.Quaternion();
  85589. this._alpha = 0;
  85590. this._beta = 0;
  85591. this._gamma = 0;
  85592. this._orientationChanged = function () {
  85593. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85594. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85595. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85596. };
  85597. this._deviceOrientation = function (evt) {
  85598. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85599. _this._beta = evt.beta !== null ? evt.beta : 0;
  85600. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85601. };
  85602. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85603. this._orientationChanged();
  85604. }
  85605. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85606. get: function () {
  85607. return this._camera;
  85608. },
  85609. set: function (camera) {
  85610. this._camera = camera;
  85611. if (this._camera != null && !this._camera.rotationQuaternion) {
  85612. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85613. }
  85614. },
  85615. enumerable: true,
  85616. configurable: true
  85617. });
  85618. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85619. window.addEventListener("orientationchange", this._orientationChanged);
  85620. window.addEventListener("deviceorientation", this._deviceOrientation);
  85621. //In certain cases, the attach control is called AFTER orientation was changed,
  85622. //So this is needed.
  85623. this._orientationChanged();
  85624. };
  85625. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85626. window.removeEventListener("orientationchange", this._orientationChanged);
  85627. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85628. };
  85629. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85630. //if no device orientation provided, don't update the rotation.
  85631. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85632. if (!this._alpha)
  85633. return;
  85634. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85635. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85636. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85637. //Mirror on XY Plane
  85638. this._camera.rotationQuaternion.z *= -1;
  85639. this._camera.rotationQuaternion.w *= -1;
  85640. };
  85641. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85642. return "FreeCameraDeviceOrientationInput";
  85643. };
  85644. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85645. return "deviceOrientation";
  85646. };
  85647. return FreeCameraDeviceOrientationInput;
  85648. }());
  85649. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85650. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85651. })(BABYLON || (BABYLON = {}));
  85652. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85653. var BABYLON;
  85654. (function (BABYLON) {
  85655. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85656. function ArcRotateCameraVRDeviceOrientationInput() {
  85657. this.alphaCorrection = 1;
  85658. this.betaCorrection = 1;
  85659. this.gammaCorrection = 1;
  85660. this._alpha = 0;
  85661. this._gamma = 0;
  85662. this._dirty = false;
  85663. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85664. }
  85665. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85666. this.camera.attachControl(element, noPreventDefault);
  85667. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85668. };
  85669. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85670. if (evt.alpha !== null) {
  85671. this._alpha = +evt.alpha | 0;
  85672. }
  85673. if (evt.gamma !== null) {
  85674. this._gamma = +evt.gamma | 0;
  85675. }
  85676. this._dirty = true;
  85677. };
  85678. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85679. if (this._dirty) {
  85680. this._dirty = false;
  85681. if (this._gamma < 0) {
  85682. this._gamma = 180 + this._gamma;
  85683. }
  85684. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85685. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85686. }
  85687. };
  85688. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85689. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85690. };
  85691. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85692. return "ArcRotateCameraVRDeviceOrientationInput";
  85693. };
  85694. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85695. return "VRDeviceOrientation";
  85696. };
  85697. return ArcRotateCameraVRDeviceOrientationInput;
  85698. }());
  85699. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85700. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85701. })(BABYLON || (BABYLON = {}));
  85702. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85703. var BABYLON;
  85704. (function (BABYLON) {
  85705. var VRCameraMetrics = /** @class */ (function () {
  85706. function VRCameraMetrics() {
  85707. this.compensateDistortion = true;
  85708. }
  85709. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85710. get: function () {
  85711. return this.hResolution / (2 * this.vResolution);
  85712. },
  85713. enumerable: true,
  85714. configurable: true
  85715. });
  85716. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85717. get: function () {
  85718. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85719. },
  85720. enumerable: true,
  85721. configurable: true
  85722. });
  85723. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85724. get: function () {
  85725. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85726. var h = (4 * meters) / this.hScreenSize;
  85727. return BABYLON.Matrix.Translation(h, 0, 0);
  85728. },
  85729. enumerable: true,
  85730. configurable: true
  85731. });
  85732. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85733. get: function () {
  85734. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85735. var h = (4 * meters) / this.hScreenSize;
  85736. return BABYLON.Matrix.Translation(-h, 0, 0);
  85737. },
  85738. enumerable: true,
  85739. configurable: true
  85740. });
  85741. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85742. get: function () {
  85743. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85744. },
  85745. enumerable: true,
  85746. configurable: true
  85747. });
  85748. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85749. get: function () {
  85750. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85751. },
  85752. enumerable: true,
  85753. configurable: true
  85754. });
  85755. VRCameraMetrics.GetDefault = function () {
  85756. var result = new VRCameraMetrics();
  85757. result.hResolution = 1280;
  85758. result.vResolution = 800;
  85759. result.hScreenSize = 0.149759993;
  85760. result.vScreenSize = 0.0935999975;
  85761. result.vScreenCenter = 0.0467999987;
  85762. result.eyeToScreenDistance = 0.0410000011;
  85763. result.lensSeparationDistance = 0.0635000020;
  85764. result.interpupillaryDistance = 0.0640000030;
  85765. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85766. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85767. result.postProcessScaleFactor = 1.714605507808412;
  85768. result.lensCenterOffset = 0.151976421;
  85769. return result;
  85770. };
  85771. return VRCameraMetrics;
  85772. }());
  85773. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85774. })(BABYLON || (BABYLON = {}));
  85775. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85776. var BABYLON;
  85777. (function (BABYLON) {
  85778. /**
  85779. * This represents a WebVR camera.
  85780. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85781. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85782. */
  85783. var WebVRFreeCamera = /** @class */ (function (_super) {
  85784. __extends(WebVRFreeCamera, _super);
  85785. /**
  85786. * Instantiates a WebVRFreeCamera.
  85787. * @param name The name of the WebVRFreeCamera
  85788. * @param position The starting anchor position for the camera
  85789. * @param scene The scene the camera belongs to
  85790. * @param webVROptions a set of customizable options for the webVRCamera
  85791. */
  85792. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85793. if (webVROptions === void 0) { webVROptions = {}; }
  85794. var _this = _super.call(this, name, position, scene) || this;
  85795. _this.webVROptions = webVROptions;
  85796. /**
  85797. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85798. */
  85799. _this._vrDevice = null;
  85800. /**
  85801. * The rawPose of the vrDevice.
  85802. */
  85803. _this.rawPose = null;
  85804. _this._specsVersion = "1.1";
  85805. _this._attached = false;
  85806. _this._descendants = [];
  85807. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85808. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85809. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85810. _this._standingMatrix = null;
  85811. /**
  85812. * Represents device position in babylon space.
  85813. */
  85814. _this.devicePosition = BABYLON.Vector3.Zero();
  85815. /**
  85816. * Represents device rotation in babylon space.
  85817. */
  85818. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85819. /**
  85820. * The scale of the device to be used when translating from device space to babylon space.
  85821. */
  85822. _this.deviceScaleFactor = 1;
  85823. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85824. _this._worldToDevice = BABYLON.Matrix.Identity();
  85825. /**
  85826. * References to the webVR controllers for the vrDevice.
  85827. */
  85828. _this.controllers = [];
  85829. /**
  85830. * Emits an event when a controller is attached.
  85831. */
  85832. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85833. /**
  85834. * Emits an event when a controller's mesh has been loaded;
  85835. */
  85836. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85837. /**
  85838. * If the rig cameras be used as parent instead of this camera.
  85839. */
  85840. _this.rigParenting = true;
  85841. _this._defaultHeight = undefined;
  85842. _this._workingVector = BABYLON.Vector3.Zero();
  85843. _this._oneVector = BABYLON.Vector3.One();
  85844. _this._workingMatrix = BABYLON.Matrix.Identity();
  85845. _this._cache.position = BABYLON.Vector3.Zero();
  85846. if (webVROptions.defaultHeight) {
  85847. _this._defaultHeight = webVROptions.defaultHeight;
  85848. _this.position.y = _this._defaultHeight;
  85849. }
  85850. _this.minZ = 0.1;
  85851. //legacy support - the compensation boolean was removed.
  85852. if (arguments.length === 5) {
  85853. _this.webVROptions = arguments[4];
  85854. }
  85855. // default webVR options
  85856. if (_this.webVROptions.trackPosition == undefined) {
  85857. _this.webVROptions.trackPosition = true;
  85858. }
  85859. if (_this.webVROptions.controllerMeshes == undefined) {
  85860. _this.webVROptions.controllerMeshes = true;
  85861. }
  85862. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  85863. _this.webVROptions.defaultLightingOnControllers = true;
  85864. }
  85865. _this.rotationQuaternion = new BABYLON.Quaternion();
  85866. if (_this.webVROptions && _this.webVROptions.positionScale) {
  85867. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  85868. }
  85869. //enable VR
  85870. var engine = _this.getEngine();
  85871. _this._onVREnabled = function (success) { if (success) {
  85872. _this.initControllers();
  85873. } };
  85874. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  85875. engine.initWebVR().add(function (event) {
  85876. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  85877. return;
  85878. }
  85879. _this._vrDevice = event.vrDisplay;
  85880. //reset the rig parameters.
  85881. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  85882. if (_this._attached) {
  85883. _this.getEngine().enableVR();
  85884. }
  85885. });
  85886. if (typeof (VRFrameData) !== "undefined")
  85887. _this._frameData = new VRFrameData();
  85888. /**
  85889. * The idea behind the following lines:
  85890. * objects that have the camera as parent should actually have the rig cameras as a parent.
  85891. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  85892. * the second will not show it correctly.
  85893. *
  85894. * To solve this - each object that has the camera as parent will be added to a protected array.
  85895. * When the rig camera renders, it will take this array and set all of those to be its children.
  85896. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  85897. * Amazing!
  85898. */
  85899. scene.onBeforeCameraRenderObservable.add(function (camera) {
  85900. if (camera.parent === _this && _this.rigParenting) {
  85901. _this._descendants = _this.getDescendants(true, function (n) {
  85902. // don't take the cameras or the controllers!
  85903. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  85904. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  85905. return !isController && !isRigCamera;
  85906. });
  85907. _this._descendants.forEach(function (node) {
  85908. node.parent = camera;
  85909. });
  85910. }
  85911. });
  85912. scene.onAfterCameraRenderObservable.add(function (camera) {
  85913. if (camera.parent === _this && _this.rigParenting) {
  85914. _this._descendants.forEach(function (node) {
  85915. node.parent = _this;
  85916. });
  85917. }
  85918. });
  85919. return _this;
  85920. }
  85921. /**
  85922. * Gets the device distance from the ground in meters.
  85923. * @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.
  85924. */
  85925. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  85926. if (this._standingMatrix) {
  85927. // Add standing matrix offset to get real offset from ground in room
  85928. this._standingMatrix.getTranslationToRef(this._workingVector);
  85929. return this._deviceRoomPosition.y + this._workingVector.y;
  85930. }
  85931. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  85932. return this._defaultHeight || 0;
  85933. };
  85934. /**
  85935. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85936. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  85937. */
  85938. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  85939. var _this = this;
  85940. if (callback === void 0) { callback = function (bool) { }; }
  85941. // Use standing matrix if available
  85942. this.getEngine().initWebVRAsync().then(function (result) {
  85943. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  85944. callback(false);
  85945. }
  85946. else {
  85947. _this._standingMatrix = new BABYLON.Matrix();
  85948. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  85949. if (!_this.getScene().useRightHandedSystem) {
  85950. [2, 6, 8, 9, 14].forEach(function (num) {
  85951. if (_this._standingMatrix) {
  85952. _this._standingMatrix.m[num] *= -1;
  85953. }
  85954. });
  85955. }
  85956. callback(true);
  85957. }
  85958. });
  85959. };
  85960. /**
  85961. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  85962. * @returns A promise with a boolean set to if the standing matrix is supported.
  85963. */
  85964. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  85965. var _this = this;
  85966. return new Promise(function (res, rej) {
  85967. _this.useStandingMatrix(function (supported) {
  85968. res(supported);
  85969. });
  85970. });
  85971. };
  85972. /**
  85973. * Disposes the camera
  85974. */
  85975. WebVRFreeCamera.prototype.dispose = function () {
  85976. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  85977. _super.prototype.dispose.call(this);
  85978. };
  85979. /**
  85980. * Gets a vrController by name.
  85981. * @param name The name of the controller to retreive
  85982. * @returns the controller matching the name specified or null if not found
  85983. */
  85984. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  85985. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  85986. var gp = _a[_i];
  85987. if (gp.hand === name) {
  85988. return gp;
  85989. }
  85990. }
  85991. return null;
  85992. };
  85993. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  85994. /**
  85995. * The controller corrisponding to the users left hand.
  85996. */
  85997. get: function () {
  85998. if (!this._leftController) {
  85999. this._leftController = this.getControllerByName("left");
  86000. }
  86001. return this._leftController;
  86002. },
  86003. enumerable: true,
  86004. configurable: true
  86005. });
  86006. ;
  86007. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86008. /**
  86009. * The controller corrisponding to the users right hand.
  86010. */
  86011. get: function () {
  86012. if (!this._rightController) {
  86013. this._rightController = this.getControllerByName("right");
  86014. }
  86015. return this._rightController;
  86016. },
  86017. enumerable: true,
  86018. configurable: true
  86019. });
  86020. ;
  86021. /**
  86022. * Casts a ray forward from the vrCamera's gaze.
  86023. * @param length Length of the ray (default: 100)
  86024. * @returns the ray corrisponding to the gaze
  86025. */
  86026. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86027. if (length === void 0) { length = 100; }
  86028. if (this.leftCamera) {
  86029. // Use left eye to avoid computation to compute center on every call
  86030. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86031. }
  86032. else {
  86033. return _super.prototype.getForwardRay.call(this, length);
  86034. }
  86035. };
  86036. /**
  86037. * Updates the camera based on device's frame data
  86038. */
  86039. WebVRFreeCamera.prototype._checkInputs = function () {
  86040. if (this._vrDevice && this._vrDevice.isPresenting) {
  86041. this._vrDevice.getFrameData(this._frameData);
  86042. this.updateFromDevice(this._frameData.pose);
  86043. }
  86044. _super.prototype._checkInputs.call(this);
  86045. };
  86046. /**
  86047. * Updates the poseControlled values based on the input device pose.
  86048. * @param poseData Pose coming from the device
  86049. */
  86050. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86051. if (poseData && poseData.orientation) {
  86052. this.rawPose = poseData;
  86053. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86054. if (this.getScene().useRightHandedSystem) {
  86055. this._deviceRoomRotationQuaternion.z *= -1;
  86056. this._deviceRoomRotationQuaternion.w *= -1;
  86057. }
  86058. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86059. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86060. if (this.getScene().useRightHandedSystem) {
  86061. this._deviceRoomPosition.z *= -1;
  86062. }
  86063. }
  86064. }
  86065. };
  86066. /**
  86067. * WebVR's attach control will start broadcasting frames to the device.
  86068. * Note that in certain browsers (chrome for example) this function must be called
  86069. * within a user-interaction callback. Example:
  86070. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86071. *
  86072. * @param element html element to attach the vrDevice to
  86073. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86074. */
  86075. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86076. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86077. this._attached = true;
  86078. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86079. if (this._vrDevice) {
  86080. this.getEngine().enableVR();
  86081. }
  86082. };
  86083. /**
  86084. * Detaches the camera from the html element and disables VR
  86085. *
  86086. * @param element html element to detach from
  86087. */
  86088. WebVRFreeCamera.prototype.detachControl = function (element) {
  86089. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86090. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86091. _super.prototype.detachControl.call(this, element);
  86092. this._attached = false;
  86093. this.getEngine().disableVR();
  86094. };
  86095. /**
  86096. * @returns the name of this class
  86097. */
  86098. WebVRFreeCamera.prototype.getClassName = function () {
  86099. return "WebVRFreeCamera";
  86100. };
  86101. /**
  86102. * Calls resetPose on the vrDisplay
  86103. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86104. */
  86105. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86106. //uses the vrDisplay's "resetPose()".
  86107. //pitch and roll won't be affected.
  86108. this._vrDevice.resetPose();
  86109. };
  86110. /**
  86111. * Updates the rig cameras (left and right eye)
  86112. */
  86113. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86114. var camLeft = this._rigCameras[0];
  86115. var camRight = this._rigCameras[1];
  86116. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86117. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86118. camLeft.position.copyFrom(this._deviceRoomPosition);
  86119. camRight.position.copyFrom(this._deviceRoomPosition);
  86120. };
  86121. /**
  86122. * Updates the cached values of the camera
  86123. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86124. */
  86125. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86126. var _this = this;
  86127. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86128. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86129. if (!this.updateCacheCalled) {
  86130. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86131. this.updateCacheCalled = true;
  86132. this.update();
  86133. }
  86134. // Set working vector to the device position in room space rotated by the new rotation
  86135. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86136. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86137. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86138. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86139. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86140. // Add translation from anchor position
  86141. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86142. this._workingVector.addInPlace(this.position);
  86143. this._workingVector.subtractInPlace(this._cache.position);
  86144. this._deviceToWorld.setTranslation(this._workingVector);
  86145. // Set an inverted matrix to be used when updating the camera
  86146. this._deviceToWorld.invertToRef(this._worldToDevice);
  86147. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86148. this.controllers.forEach(function (controller) {
  86149. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86150. controller.update();
  86151. });
  86152. }
  86153. if (!ignoreParentClass) {
  86154. _super.prototype._updateCache.call(this);
  86155. }
  86156. this.updateCacheCalled = false;
  86157. };
  86158. /**
  86159. * Updates the current device position and rotation in the babylon world
  86160. */
  86161. WebVRFreeCamera.prototype.update = function () {
  86162. // Get current device position in babylon world
  86163. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86164. // Get current device rotation in babylon world
  86165. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86166. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86167. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86168. _super.prototype.update.call(this);
  86169. };
  86170. /**
  86171. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86172. * @returns an identity matrix
  86173. */
  86174. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86175. return BABYLON.Matrix.Identity();
  86176. };
  86177. /**
  86178. * This function is called by the two RIG cameras.
  86179. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86180. */
  86181. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86182. var _this = this;
  86183. // Update the parent camera prior to using a child camera to avoid desynchronization
  86184. var parentCamera = this._cameraRigParams["parentCamera"];
  86185. parentCamera._updateCache();
  86186. //WebVR 1.1
  86187. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86188. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86189. if (!this.getScene().useRightHandedSystem) {
  86190. [2, 6, 8, 9, 14].forEach(function (num) {
  86191. _this._webvrViewMatrix.m[num] *= -1;
  86192. });
  86193. }
  86194. // update the camera rotation matrix
  86195. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86196. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86197. // Computing target and final matrix
  86198. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86199. // should the view matrix be updated with scale and position offset?
  86200. if (parentCamera.deviceScaleFactor !== 1) {
  86201. this._webvrViewMatrix.invert();
  86202. // scale the position, if set
  86203. if (parentCamera.deviceScaleFactor) {
  86204. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86205. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86206. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86207. }
  86208. this._webvrViewMatrix.invert();
  86209. }
  86210. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86211. return this._webvrViewMatrix;
  86212. };
  86213. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86214. var _this = this;
  86215. var parentCamera = this.parent;
  86216. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86217. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86218. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86219. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86220. //babylon compatible matrix
  86221. if (!this.getScene().useRightHandedSystem) {
  86222. [8, 9, 10, 11].forEach(function (num) {
  86223. _this._projectionMatrix.m[num] *= -1;
  86224. });
  86225. }
  86226. return this._projectionMatrix;
  86227. };
  86228. /**
  86229. * Initializes the controllers and their meshes
  86230. */
  86231. WebVRFreeCamera.prototype.initControllers = function () {
  86232. var _this = this;
  86233. this.controllers = [];
  86234. var manager = this.getScene().gamepadManager;
  86235. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86236. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86237. var webVrController = gamepad;
  86238. if (webVrController.defaultModel) {
  86239. webVrController.defaultModel.setEnabled(false);
  86240. }
  86241. if (webVrController.hand === "right") {
  86242. _this._rightController = null;
  86243. }
  86244. if (webVrController.hand === "left") {
  86245. _this._leftController = null;
  86246. }
  86247. var controllerIndex = _this.controllers.indexOf(webVrController);
  86248. if (controllerIndex !== -1) {
  86249. _this.controllers.splice(controllerIndex, 1);
  86250. }
  86251. }
  86252. });
  86253. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86254. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86255. var webVrController_1 = gamepad;
  86256. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86257. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86258. if (_this.webVROptions.controllerMeshes) {
  86259. if (webVrController_1.defaultModel) {
  86260. webVrController_1.defaultModel.setEnabled(true);
  86261. }
  86262. else {
  86263. // Load the meshes
  86264. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86265. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86266. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86267. if (_this.webVROptions.defaultLightingOnControllers) {
  86268. if (!_this._lightOnControllers) {
  86269. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86270. }
  86271. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86272. var children = mesh.getChildren();
  86273. if (children.length !== 0) {
  86274. children.forEach(function (mesh) {
  86275. light.includedOnlyMeshes.push(mesh);
  86276. activateLightOnSubMeshes_1(mesh, light);
  86277. });
  86278. }
  86279. };
  86280. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86281. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86282. }
  86283. });
  86284. }
  86285. }
  86286. webVrController_1.attachToPoseControlledCamera(_this);
  86287. // since this is async - sanity check. Is the controller already stored?
  86288. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86289. //add to the controllers array
  86290. _this.controllers.push(webVrController_1);
  86291. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86292. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86293. // So we're overriding setting left & right manually to be sure
  86294. var firstViveWandDetected = false;
  86295. for (var i = 0; i < _this.controllers.length; i++) {
  86296. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86297. if (!firstViveWandDetected) {
  86298. firstViveWandDetected = true;
  86299. _this.controllers[i].hand = "left";
  86300. }
  86301. else {
  86302. _this.controllers[i].hand = "right";
  86303. }
  86304. }
  86305. }
  86306. //did we find enough controllers? Great! let the developer know.
  86307. if (_this.controllers.length >= 2) {
  86308. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86309. }
  86310. }
  86311. }
  86312. });
  86313. };
  86314. return WebVRFreeCamera;
  86315. }(BABYLON.FreeCamera));
  86316. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86317. })(BABYLON || (BABYLON = {}));
  86318. //# sourceMappingURL=babylon.webVRCamera.js.map
  86319. var BABYLON;
  86320. (function (BABYLON) {
  86321. // We're mainly based on the logic defined into the FreeCamera code
  86322. /**
  86323. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86324. * being tilted forward or back and left or right.
  86325. */
  86326. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86327. __extends(DeviceOrientationCamera, _super);
  86328. /**
  86329. * Creates a new device orientation camera
  86330. * @param name The name of the camera
  86331. * @param position The start position camera
  86332. * @param scene The scene the camera belongs to
  86333. */
  86334. function DeviceOrientationCamera(name, position, scene) {
  86335. var _this = _super.call(this, name, position, scene) || this;
  86336. _this._quaternionCache = new BABYLON.Quaternion();
  86337. _this.inputs.addDeviceOrientation();
  86338. return _this;
  86339. }
  86340. /**
  86341. * Gets the current instance class name ("DeviceOrientationCamera").
  86342. * This helps avoiding instanceof at run time.
  86343. * @returns the class name
  86344. */
  86345. DeviceOrientationCamera.prototype.getClassName = function () {
  86346. return "DeviceOrientationCamera";
  86347. };
  86348. /**
  86349. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86350. */
  86351. DeviceOrientationCamera.prototype._checkInputs = function () {
  86352. _super.prototype._checkInputs.call(this);
  86353. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86354. if (this._initialQuaternion) {
  86355. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86356. }
  86357. };
  86358. /**
  86359. * Reset the camera to its default orientation on the specified axis only.
  86360. * @param axis The axis to reset
  86361. */
  86362. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86363. var _this = this;
  86364. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86365. //can only work if this camera has a rotation quaternion already.
  86366. if (!this.rotationQuaternion)
  86367. return;
  86368. if (!this._initialQuaternion) {
  86369. this._initialQuaternion = new BABYLON.Quaternion();
  86370. }
  86371. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86372. ['x', 'y', 'z'].forEach(function (axisName) {
  86373. if (!axis[axisName]) {
  86374. _this._initialQuaternion[axisName] = 0;
  86375. }
  86376. else {
  86377. _this._initialQuaternion[axisName] *= -1;
  86378. }
  86379. });
  86380. this._initialQuaternion.normalize();
  86381. //force rotation update
  86382. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86383. };
  86384. return DeviceOrientationCamera;
  86385. }(BABYLON.FreeCamera));
  86386. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86387. })(BABYLON || (BABYLON = {}));
  86388. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86389. var BABYLON;
  86390. (function (BABYLON) {
  86391. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86392. __extends(VRDeviceOrientationFreeCamera, _super);
  86393. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86394. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86395. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86396. var _this = _super.call(this, name, position, scene) || this;
  86397. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86398. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86399. return _this;
  86400. }
  86401. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86402. return "VRDeviceOrientationFreeCamera";
  86403. };
  86404. return VRDeviceOrientationFreeCamera;
  86405. }(BABYLON.DeviceOrientationCamera));
  86406. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86407. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86408. __extends(VRDeviceOrientationGamepadCamera, _super);
  86409. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86410. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86411. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86412. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86413. _this.inputs.addGamepad();
  86414. return _this;
  86415. }
  86416. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86417. return "VRDeviceOrientationGamepadCamera";
  86418. };
  86419. return VRDeviceOrientationGamepadCamera;
  86420. }(VRDeviceOrientationFreeCamera));
  86421. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86422. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86423. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86424. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86425. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86426. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86427. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86428. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86429. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86430. _this.inputs.addVRDeviceOrientation();
  86431. return _this;
  86432. }
  86433. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86434. return "VRDeviceOrientationArcRotateCamera";
  86435. };
  86436. return VRDeviceOrientationArcRotateCamera;
  86437. }(BABYLON.ArcRotateCamera));
  86438. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86439. })(BABYLON || (BABYLON = {}));
  86440. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86441. var BABYLON;
  86442. (function (BABYLON) {
  86443. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86444. __extends(AnaglyphFreeCamera, _super);
  86445. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86446. var _this = _super.call(this, name, position, scene) || this;
  86447. _this.interaxialDistance = interaxialDistance;
  86448. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86449. return _this;
  86450. }
  86451. AnaglyphFreeCamera.prototype.getClassName = function () {
  86452. return "AnaglyphFreeCamera";
  86453. };
  86454. return AnaglyphFreeCamera;
  86455. }(BABYLON.FreeCamera));
  86456. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86457. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86458. __extends(AnaglyphArcRotateCamera, _super);
  86459. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86460. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86461. _this.interaxialDistance = interaxialDistance;
  86462. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86463. return _this;
  86464. }
  86465. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  86466. return "AnaglyphArcRotateCamera";
  86467. };
  86468. return AnaglyphArcRotateCamera;
  86469. }(BABYLON.ArcRotateCamera));
  86470. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  86471. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  86472. __extends(AnaglyphGamepadCamera, _super);
  86473. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  86474. var _this = _super.call(this, name, position, scene) || this;
  86475. _this.interaxialDistance = interaxialDistance;
  86476. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86477. return _this;
  86478. }
  86479. AnaglyphGamepadCamera.prototype.getClassName = function () {
  86480. return "AnaglyphGamepadCamera";
  86481. };
  86482. return AnaglyphGamepadCamera;
  86483. }(BABYLON.GamepadCamera));
  86484. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  86485. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  86486. __extends(AnaglyphUniversalCamera, _super);
  86487. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  86488. var _this = _super.call(this, name, position, scene) || this;
  86489. _this.interaxialDistance = interaxialDistance;
  86490. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86491. return _this;
  86492. }
  86493. AnaglyphUniversalCamera.prototype.getClassName = function () {
  86494. return "AnaglyphUniversalCamera";
  86495. };
  86496. return AnaglyphUniversalCamera;
  86497. }(BABYLON.UniversalCamera));
  86498. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  86499. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  86500. __extends(StereoscopicFreeCamera, _super);
  86501. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86502. var _this = _super.call(this, name, position, scene) || this;
  86503. _this.interaxialDistance = interaxialDistance;
  86504. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86505. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86506. return _this;
  86507. }
  86508. StereoscopicFreeCamera.prototype.getClassName = function () {
  86509. return "StereoscopicFreeCamera";
  86510. };
  86511. return StereoscopicFreeCamera;
  86512. }(BABYLON.FreeCamera));
  86513. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  86514. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  86515. __extends(StereoscopicArcRotateCamera, _super);
  86516. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  86517. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86518. _this.interaxialDistance = interaxialDistance;
  86519. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86520. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86521. return _this;
  86522. }
  86523. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  86524. return "StereoscopicArcRotateCamera";
  86525. };
  86526. return StereoscopicArcRotateCamera;
  86527. }(BABYLON.ArcRotateCamera));
  86528. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  86529. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  86530. __extends(StereoscopicGamepadCamera, _super);
  86531. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86532. var _this = _super.call(this, name, position, scene) || this;
  86533. _this.interaxialDistance = interaxialDistance;
  86534. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86535. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86536. return _this;
  86537. }
  86538. StereoscopicGamepadCamera.prototype.getClassName = function () {
  86539. return "StereoscopicGamepadCamera";
  86540. };
  86541. return StereoscopicGamepadCamera;
  86542. }(BABYLON.GamepadCamera));
  86543. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  86544. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  86545. __extends(StereoscopicUniversalCamera, _super);
  86546. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86547. var _this = _super.call(this, name, position, scene) || this;
  86548. _this.interaxialDistance = interaxialDistance;
  86549. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86550. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86551. return _this;
  86552. }
  86553. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86554. return "StereoscopicUniversalCamera";
  86555. };
  86556. return StereoscopicUniversalCamera;
  86557. }(BABYLON.UniversalCamera));
  86558. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86559. })(BABYLON || (BABYLON = {}));
  86560. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86561. var BABYLON;
  86562. (function (BABYLON) {
  86563. var VRExperienceHelperGazer = /** @class */ (function () {
  86564. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86565. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86566. this.scene = scene;
  86567. this._pointerDownOnMeshAsked = false;
  86568. this._isActionableMesh = false;
  86569. this._teleportationRequestInitiated = false;
  86570. this._teleportationBackRequestInitiated = false;
  86571. this._dpadPressed = true;
  86572. this._activePointer = false;
  86573. this._id = VRExperienceHelperGazer._idCounter++;
  86574. // Gaze tracker
  86575. if (!gazeTrackerToClone) {
  86576. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86577. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86578. this._gazeTracker.isPickable = false;
  86579. this._gazeTracker.isVisible = false;
  86580. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86581. targetMat.specularColor = BABYLON.Color3.Black();
  86582. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86583. targetMat.backFaceCulling = false;
  86584. this._gazeTracker.material = targetMat;
  86585. }
  86586. else {
  86587. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86588. }
  86589. }
  86590. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86591. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86592. };
  86593. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86594. this._pointerDownOnMeshAsked = true;
  86595. if (this._currentMeshSelected && this._currentHit) {
  86596. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86597. }
  86598. };
  86599. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86600. if (this._currentMeshSelected && this._currentHit) {
  86601. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86602. }
  86603. this._pointerDownOnMeshAsked = false;
  86604. };
  86605. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86606. this._activePointer = true;
  86607. };
  86608. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86609. this._activePointer = false;
  86610. };
  86611. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86612. };
  86613. VRExperienceHelperGazer.prototype.dispose = function () {
  86614. this._interactionsEnabled = false;
  86615. this._teleportationEnabled = false;
  86616. };
  86617. VRExperienceHelperGazer._idCounter = 0;
  86618. return VRExperienceHelperGazer;
  86619. }());
  86620. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86621. __extends(VRExperienceHelperControllerGazer, _super);
  86622. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86623. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86624. _this.webVRController = webVRController;
  86625. // Laser pointer
  86626. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86627. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86628. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86629. laserPointerMaterial.alpha = 0.6;
  86630. _this._laserPointer.material = laserPointerMaterial;
  86631. _this._laserPointer.rotation.x = Math.PI / 2;
  86632. _this._laserPointer.position.z = -0.5;
  86633. _this._laserPointer.isVisible = false;
  86634. if (!webVRController.mesh) {
  86635. // Create an empty mesh that is used prior to loading the high quality model
  86636. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86637. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86638. preloadPointerPose.rotation.x = -0.7;
  86639. preloadMesh.addChild(preloadPointerPose);
  86640. webVRController.attachToMesh(preloadMesh);
  86641. }
  86642. _this._setLaserPointerParent(webVRController.mesh);
  86643. return _this;
  86644. }
  86645. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86646. return this.webVRController.getForwardRay(length);
  86647. };
  86648. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86649. _super.prototype._activatePointer.call(this);
  86650. this._laserPointer.isVisible = true;
  86651. };
  86652. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86653. _super.prototype._deactivatePointer.call(this);
  86654. this._laserPointer.isVisible = false;
  86655. };
  86656. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86657. this._laserPointer.material.emissiveColor = color;
  86658. };
  86659. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86660. var makeNotPick = function (root) {
  86661. root.name += " laserPointer";
  86662. root.getChildMeshes().forEach(function (c) {
  86663. makeNotPick(c);
  86664. });
  86665. };
  86666. makeNotPick(mesh);
  86667. var childMeshes = mesh.getChildMeshes();
  86668. this.webVRController._pointingPoseNode = null;
  86669. for (var i = 0; i < childMeshes.length; i++) {
  86670. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86671. mesh = childMeshes[i];
  86672. this.webVRController._pointingPoseNode = mesh;
  86673. break;
  86674. }
  86675. }
  86676. this._laserPointer.parent = mesh;
  86677. };
  86678. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86679. this._laserPointer.scaling.y = distance;
  86680. this._laserPointer.position.z = -distance / 2;
  86681. };
  86682. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86683. _super.prototype.dispose.call(this);
  86684. this._laserPointer.dispose();
  86685. };
  86686. return VRExperienceHelperControllerGazer;
  86687. }(VRExperienceHelperGazer));
  86688. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86689. __extends(VRExperienceHelperCameraGazer, _super);
  86690. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86691. var _this = _super.call(this, scene) || this;
  86692. _this.getCamera = getCamera;
  86693. return _this;
  86694. }
  86695. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86696. var camera = this.getCamera();
  86697. if (camera) {
  86698. return camera.getForwardRay(length);
  86699. }
  86700. else {
  86701. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86702. }
  86703. };
  86704. return VRExperienceHelperCameraGazer;
  86705. }(VRExperienceHelperGazer));
  86706. /**
  86707. * Helps to quickly add VR support to an existing scene.
  86708. * See http://doc.babylonjs.com/how_to/webvr_helper
  86709. */
  86710. var VRExperienceHelper = /** @class */ (function () {
  86711. /**
  86712. * Instantiates a VRExperienceHelper.
  86713. * Helps to quickly add VR support to an existing scene.
  86714. * @param scene The scene the VRExperienceHelper belongs to.
  86715. * @param webVROptions Options to modify the vr experience helper's behavior.
  86716. */
  86717. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86718. if (webVROptions === void 0) { webVROptions = {}; }
  86719. var _this = this;
  86720. this.webVROptions = webVROptions;
  86721. // Can the system support WebVR, even if a headset isn't plugged in?
  86722. this._webVRsupported = false;
  86723. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86724. this._webVRready = false;
  86725. // Are we waiting for the requestPresent callback to complete?
  86726. this._webVRrequesting = false;
  86727. // Are we presenting to the headset right now?
  86728. this._webVRpresenting = false;
  86729. // Are we presenting in the fullscreen fallback?
  86730. this._fullscreenVRpresenting = false;
  86731. /**
  86732. * Observable raised when entering VR.
  86733. */
  86734. this.onEnteringVRObservable = new BABYLON.Observable();
  86735. /**
  86736. * Observable raised when exiting VR.
  86737. */
  86738. this.onExitingVRObservable = new BABYLON.Observable();
  86739. /**
  86740. * Observable raised when controller mesh is loaded.
  86741. */
  86742. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86743. this._useCustomVRButton = false;
  86744. this._teleportationRequested = false;
  86745. this._teleportActive = false;
  86746. this._floorMeshesCollection = [];
  86747. this._rotationAllowed = true;
  86748. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86749. this._rotationRightAsked = false;
  86750. this._rotationLeftAsked = false;
  86751. this._isDefaultTeleportationTarget = true;
  86752. this._teleportationFillColor = "#444444";
  86753. this._teleportationBorderColor = "#FFFFFF";
  86754. this._rotationAngle = 0;
  86755. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86756. this._padSensibilityUp = 0.65;
  86757. this._padSensibilityDown = 0.35;
  86758. this.leftController = null;
  86759. this.rightController = null;
  86760. /**
  86761. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86762. */
  86763. this.onNewMeshSelected = new BABYLON.Observable();
  86764. /**
  86765. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86766. */
  86767. this.onNewMeshPicked = new BABYLON.Observable();
  86768. /**
  86769. * Observable raised before camera teleportation
  86770. */
  86771. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86772. /**
  86773. * Observable raised after camera teleportation
  86774. */
  86775. this.onAfterCameraTeleport = new BABYLON.Observable();
  86776. /**
  86777. * Observable raised when current selected mesh gets unselected
  86778. */
  86779. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86780. /**
  86781. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86782. */
  86783. this.teleportationEnabled = true;
  86784. this._teleportationInitialized = false;
  86785. this._interactionsEnabled = false;
  86786. this._interactionsRequested = false;
  86787. this._displayGaze = true;
  86788. this._displayLaserPointer = true;
  86789. this._onResize = function () {
  86790. _this.moveButtonToBottomRight();
  86791. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86792. _this.exitVR();
  86793. }
  86794. };
  86795. this._onFullscreenChange = function () {
  86796. if (document.fullscreen !== undefined) {
  86797. _this._fullscreenVRpresenting = document.fullscreen;
  86798. }
  86799. else if (document.mozFullScreen !== undefined) {
  86800. _this._fullscreenVRpresenting = document.mozFullScreen;
  86801. }
  86802. else if (document.webkitIsFullScreen !== undefined) {
  86803. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86804. }
  86805. else if (document.msIsFullScreen !== undefined) {
  86806. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86807. }
  86808. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86809. _this.exitVR();
  86810. if (!_this._useCustomVRButton) {
  86811. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86812. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86813. }
  86814. }
  86815. };
  86816. this.beforeRender = function () {
  86817. if (_this.leftController && _this.leftController._activePointer) {
  86818. _this._castRayAndSelectObject(_this.leftController);
  86819. }
  86820. if (_this.rightController && _this.rightController._activePointer) {
  86821. _this._castRayAndSelectObject(_this.rightController);
  86822. }
  86823. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86824. _this._castRayAndSelectObject(_this._cameraGazer);
  86825. }
  86826. else {
  86827. _this._cameraGazer._gazeTracker.isVisible = false;
  86828. }
  86829. };
  86830. this._onNewGamepadConnected = function (gamepad) {
  86831. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86832. if (gamepad.leftStick) {
  86833. gamepad.onleftstickchanged(function (stickValues) {
  86834. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86835. // Listening to classic/xbox gamepad only if no VR controller is active
  86836. if ((!_this.leftController && !_this.rightController) ||
  86837. ((_this.leftController && !_this.leftController._activePointer) &&
  86838. (_this.rightController && !_this.rightController._activePointer))) {
  86839. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  86840. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  86841. }
  86842. }
  86843. });
  86844. }
  86845. if (gamepad.rightStick) {
  86846. gamepad.onrightstickchanged(function (stickValues) {
  86847. if (_this._teleportationInitialized) {
  86848. _this._checkRotate(stickValues, _this._cameraGazer);
  86849. }
  86850. });
  86851. }
  86852. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  86853. gamepad.onbuttondown(function (buttonPressed) {
  86854. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86855. _this._cameraGazer._selectionPointerDown();
  86856. }
  86857. });
  86858. gamepad.onbuttonup(function (buttonPressed) {
  86859. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  86860. _this._cameraGazer._selectionPointerUp();
  86861. }
  86862. });
  86863. }
  86864. }
  86865. else {
  86866. var webVRController = gamepad;
  86867. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  86868. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  86869. _this.rightController = controller;
  86870. }
  86871. else {
  86872. _this.leftController = controller;
  86873. }
  86874. _this._tryEnableInteractionOnController(controller);
  86875. }
  86876. };
  86877. // 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
  86878. this._tryEnableInteractionOnController = function (controller) {
  86879. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  86880. _this._enableInteractionOnController(controller);
  86881. }
  86882. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  86883. _this._enableTeleportationOnController(controller);
  86884. }
  86885. };
  86886. this._onNewGamepadDisconnected = function (gamepad) {
  86887. if (gamepad instanceof BABYLON.WebVRController) {
  86888. if (gamepad.hand === "left" && _this.leftController != null) {
  86889. _this.leftController.dispose();
  86890. _this.leftController = null;
  86891. }
  86892. if (gamepad.hand === "right" && _this.rightController != null) {
  86893. _this.rightController.dispose();
  86894. _this.rightController = null;
  86895. }
  86896. }
  86897. };
  86898. this._workingVector = BABYLON.Vector3.Zero();
  86899. this._workingQuaternion = BABYLON.Quaternion.Identity();
  86900. this._workingMatrix = BABYLON.Matrix.Identity();
  86901. this._scene = scene;
  86902. this._canvas = scene.getEngine().getRenderingCanvas();
  86903. // Parse options
  86904. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  86905. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  86906. }
  86907. if (webVROptions.createDeviceOrientationCamera === undefined) {
  86908. webVROptions.createDeviceOrientationCamera = true;
  86909. }
  86910. if (webVROptions.defaultHeight === undefined) {
  86911. webVROptions.defaultHeight = 1.7;
  86912. }
  86913. if (webVROptions.useCustomVRButton) {
  86914. this._useCustomVRButton = true;
  86915. if (webVROptions.customVRButton) {
  86916. this._btnVR = webVROptions.customVRButton;
  86917. }
  86918. }
  86919. if (webVROptions.rayLength) {
  86920. this._rayLength = webVROptions.rayLength;
  86921. }
  86922. this._defaultHeight = webVROptions.defaultHeight;
  86923. if (webVROptions.positionScale) {
  86924. this._rayLength *= webVROptions.positionScale;
  86925. this._defaultHeight *= webVROptions.positionScale;
  86926. }
  86927. // Set position
  86928. if (this._scene.activeCamera) {
  86929. this._position = this._scene.activeCamera.position.clone();
  86930. }
  86931. else {
  86932. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  86933. }
  86934. // Set non-vr camera
  86935. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  86936. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  86937. // Copy data from existing camera
  86938. if (this._scene.activeCamera) {
  86939. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  86940. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  86941. // Set rotation from previous camera
  86942. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  86943. var targetCamera = this._scene.activeCamera;
  86944. if (targetCamera.rotationQuaternion) {
  86945. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  86946. }
  86947. else {
  86948. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  86949. }
  86950. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  86951. }
  86952. }
  86953. this._scene.activeCamera = this._deviceOrientationCamera;
  86954. if (this._canvas) {
  86955. this._scene.activeCamera.attachControl(this._canvas);
  86956. }
  86957. }
  86958. else {
  86959. this._existingCamera = this._scene.activeCamera;
  86960. }
  86961. // Create VR cameras
  86962. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  86963. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  86964. }
  86965. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  86966. this._webVRCamera.useStandingMatrix();
  86967. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  86968. // Create default button
  86969. if (!this._useCustomVRButton) {
  86970. this._btnVR = document.createElement("BUTTON");
  86971. this._btnVR.className = "babylonVRicon";
  86972. this._btnVR.id = "babylonVRiconbtn";
  86973. this._btnVR.title = "Click to switch to VR";
  86974. 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) }";
  86975. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  86976. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  86977. // css += ".babylonVRicon.vrdisplaysupported { }";
  86978. // css += ".babylonVRicon.vrdisplayready { }";
  86979. // css += ".babylonVRicon.vrdisplayrequesting { }";
  86980. var style = document.createElement('style');
  86981. style.appendChild(document.createTextNode(css));
  86982. document.getElementsByTagName('head')[0].appendChild(style);
  86983. this.moveButtonToBottomRight();
  86984. }
  86985. // VR button click event
  86986. if (this._btnVR) {
  86987. this._btnVR.addEventListener("click", function () {
  86988. if (!_this.isInVRMode) {
  86989. _this.enterVR();
  86990. }
  86991. else {
  86992. _this.exitVR();
  86993. }
  86994. });
  86995. }
  86996. // Window events
  86997. window.addEventListener("resize", this._onResize);
  86998. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  86999. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87000. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87001. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87002. // Display vr button when headset is connected
  87003. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87004. this.displayVRButton();
  87005. }
  87006. else {
  87007. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87008. if (e.vrDisplay) {
  87009. _this.displayVRButton();
  87010. }
  87011. });
  87012. }
  87013. // Exiting VR mode using 'ESC' key on desktop
  87014. this._onKeyDown = function (event) {
  87015. if (event.keyCode === 27 && _this.isInVRMode) {
  87016. _this.exitVR();
  87017. }
  87018. };
  87019. document.addEventListener("keydown", this._onKeyDown);
  87020. // Exiting VR mode double tapping the touch screen
  87021. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87022. if (_this.isInVRMode) {
  87023. _this.exitVR();
  87024. if (_this._fullscreenVRpresenting) {
  87025. _this._scene.getEngine().switchFullscreen(true);
  87026. }
  87027. }
  87028. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87029. // Listen for WebVR display changes
  87030. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87031. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87032. this._onVRRequestPresentStart = function () {
  87033. _this._webVRrequesting = true;
  87034. _this.updateButtonVisibility();
  87035. };
  87036. this._onVRRequestPresentComplete = function (success) {
  87037. _this._webVRrequesting = false;
  87038. _this.updateButtonVisibility();
  87039. };
  87040. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87041. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87042. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87043. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87044. scene.onDisposeObservable.add(function () {
  87045. _this.dispose();
  87046. });
  87047. // Gamepad connection events
  87048. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87049. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87050. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87051. this.updateButtonVisibility();
  87052. //create easing functions
  87053. this._circleEase = new BABYLON.CircleEase();
  87054. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87055. }
  87056. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87057. /** Return this.onEnteringVRObservable
  87058. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87059. */
  87060. get: function () {
  87061. return this.onEnteringVRObservable;
  87062. },
  87063. enumerable: true,
  87064. configurable: true
  87065. });
  87066. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87067. /** Return this.onExitingVRObservable
  87068. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87069. */
  87070. get: function () {
  87071. return this.onExitingVRObservable;
  87072. },
  87073. enumerable: true,
  87074. configurable: true
  87075. });
  87076. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87077. /** Return this.onControllerMeshLoadedObservable
  87078. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87079. */
  87080. get: function () {
  87081. return this.onControllerMeshLoadedObservable;
  87082. },
  87083. enumerable: true,
  87084. configurable: true
  87085. });
  87086. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87087. /**
  87088. * The mesh used to display where the user is going to teleport.
  87089. */
  87090. get: function () {
  87091. return this._teleportationTarget;
  87092. },
  87093. /**
  87094. * Sets the mesh to be used to display where the user is going to teleport.
  87095. */
  87096. set: function (value) {
  87097. if (value) {
  87098. value.name = "teleportationTarget";
  87099. this._isDefaultTeleportationTarget = false;
  87100. this._teleportationTarget = value;
  87101. }
  87102. },
  87103. enumerable: true,
  87104. configurable: true
  87105. });
  87106. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87107. /**
  87108. * The mesh used to display where the user is selecting,
  87109. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87110. * See http://doc.babylonjs.com/resources/baking_transformations
  87111. */
  87112. get: function () {
  87113. return this._cameraGazer._gazeTracker;
  87114. },
  87115. set: function (value) {
  87116. if (value) {
  87117. this._cameraGazer._gazeTracker = value;
  87118. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87119. this._cameraGazer._gazeTracker.isPickable = false;
  87120. this._cameraGazer._gazeTracker.isVisible = false;
  87121. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87122. if (this.leftController) {
  87123. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87124. }
  87125. if (this.rightController) {
  87126. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87127. }
  87128. }
  87129. },
  87130. enumerable: true,
  87131. configurable: true
  87132. });
  87133. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87134. /**
  87135. * If the ray of the gaze should be displayed.
  87136. */
  87137. get: function () {
  87138. return this._displayGaze;
  87139. },
  87140. /**
  87141. * Sets if the ray of the gaze should be displayed.
  87142. */
  87143. set: function (value) {
  87144. this._displayGaze = value;
  87145. if (!value) {
  87146. this._cameraGazer._gazeTracker.isVisible = false;
  87147. if (this.leftController) {
  87148. this.leftController._gazeTracker.isVisible = false;
  87149. }
  87150. if (this.rightController) {
  87151. this.rightController._gazeTracker.isVisible = false;
  87152. }
  87153. }
  87154. },
  87155. enumerable: true,
  87156. configurable: true
  87157. });
  87158. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87159. /**
  87160. * If the ray of the LaserPointer should be displayed.
  87161. */
  87162. get: function () {
  87163. return this._displayLaserPointer;
  87164. },
  87165. /**
  87166. * Sets if the ray of the LaserPointer should be displayed.
  87167. */
  87168. set: function (value) {
  87169. this._displayLaserPointer = value;
  87170. if (!value) {
  87171. if (this.rightController) {
  87172. this.rightController._deactivatePointer();
  87173. this.rightController._gazeTracker.isVisible = false;
  87174. }
  87175. if (this.leftController) {
  87176. this.leftController._deactivatePointer();
  87177. this.leftController._gazeTracker.isVisible = false;
  87178. }
  87179. }
  87180. else {
  87181. if (this.rightController) {
  87182. this.rightController._activatePointer();
  87183. }
  87184. else if (this.leftController) {
  87185. this.leftController._activatePointer();
  87186. }
  87187. }
  87188. },
  87189. enumerable: true,
  87190. configurable: true
  87191. });
  87192. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87193. /**
  87194. * The deviceOrientationCamera used as the camera when not in VR.
  87195. */
  87196. get: function () {
  87197. return this._deviceOrientationCamera;
  87198. },
  87199. enumerable: true,
  87200. configurable: true
  87201. });
  87202. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87203. /**
  87204. * Based on the current WebVR support, returns the current VR camera used.
  87205. */
  87206. get: function () {
  87207. if (this._webVRready) {
  87208. return this._webVRCamera;
  87209. }
  87210. else {
  87211. return this._scene.activeCamera;
  87212. }
  87213. },
  87214. enumerable: true,
  87215. configurable: true
  87216. });
  87217. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87218. /**
  87219. * The webVRCamera which is used when in VR.
  87220. */
  87221. get: function () {
  87222. return this._webVRCamera;
  87223. },
  87224. enumerable: true,
  87225. configurable: true
  87226. });
  87227. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87228. /**
  87229. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87230. */
  87231. get: function () {
  87232. return this._vrDeviceOrientationCamera;
  87233. },
  87234. enumerable: true,
  87235. configurable: true
  87236. });
  87237. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87238. get: function () {
  87239. var result = this._cameraGazer._teleportationRequestInitiated
  87240. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87241. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87242. return result;
  87243. },
  87244. enumerable: true,
  87245. configurable: true
  87246. });
  87247. // Raised when one of the controller has loaded successfully its associated default mesh
  87248. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87249. if (this.leftController && this.leftController.webVRController == webVRController) {
  87250. if (webVRController.mesh) {
  87251. this.leftController._setLaserPointerParent(webVRController.mesh);
  87252. }
  87253. }
  87254. if (this.rightController && this.rightController.webVRController == webVRController) {
  87255. if (webVRController.mesh) {
  87256. this.rightController._setLaserPointerParent(webVRController.mesh);
  87257. }
  87258. }
  87259. try {
  87260. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87261. }
  87262. catch (err) {
  87263. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87264. }
  87265. };
  87266. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87267. /**
  87268. * Gets a value indicating if we are currently in VR mode.
  87269. */
  87270. get: function () {
  87271. return this._webVRpresenting || this._fullscreenVRpresenting;
  87272. },
  87273. enumerable: true,
  87274. configurable: true
  87275. });
  87276. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87277. var vrDisplay = this._scene.getEngine().getVRDevice();
  87278. if (vrDisplay) {
  87279. var wasPresenting = this._webVRpresenting;
  87280. // A VR display is connected
  87281. this._webVRpresenting = vrDisplay.isPresenting;
  87282. if (wasPresenting && !this._webVRpresenting)
  87283. this.exitVR();
  87284. }
  87285. else {
  87286. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87287. }
  87288. this.updateButtonVisibility();
  87289. };
  87290. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87291. this._webVRsupported = eventArgs.vrSupported;
  87292. this._webVRready = !!eventArgs.vrDisplay;
  87293. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87294. this.updateButtonVisibility();
  87295. };
  87296. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87297. if (this._canvas && !this._useCustomVRButton) {
  87298. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87299. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87300. }
  87301. };
  87302. VRExperienceHelper.prototype.displayVRButton = function () {
  87303. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87304. document.body.appendChild(this._btnVR);
  87305. this._btnVRDisplayed = true;
  87306. }
  87307. };
  87308. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87309. if (!this._btnVR || this._useCustomVRButton) {
  87310. return;
  87311. }
  87312. this._btnVR.className = "babylonVRicon";
  87313. if (this.isInVRMode) {
  87314. this._btnVR.className += " vrdisplaypresenting";
  87315. }
  87316. else {
  87317. if (this._webVRready)
  87318. this._btnVR.className += " vrdisplayready";
  87319. if (this._webVRsupported)
  87320. this._btnVR.className += " vrdisplaysupported";
  87321. if (this._webVRrequesting)
  87322. this._btnVR.className += " vrdisplayrequesting";
  87323. }
  87324. };
  87325. /**
  87326. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87327. * Otherwise, will use the fullscreen API.
  87328. */
  87329. VRExperienceHelper.prototype.enterVR = function () {
  87330. if (this.onEnteringVRObservable) {
  87331. try {
  87332. this.onEnteringVRObservable.notifyObservers(this);
  87333. }
  87334. catch (err) {
  87335. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87336. }
  87337. }
  87338. if (this._scene.activeCamera) {
  87339. this._position = this._scene.activeCamera.position.clone();
  87340. // make sure that we return to the last active camera
  87341. this._existingCamera = this._scene.activeCamera;
  87342. }
  87343. if (this._webVRrequesting)
  87344. return;
  87345. // If WebVR is supported and a headset is connected
  87346. if (this._webVRready) {
  87347. if (!this._webVRpresenting) {
  87348. this._webVRCamera.position = this._position;
  87349. this._scene.activeCamera = this._webVRCamera;
  87350. }
  87351. }
  87352. else if (this._vrDeviceOrientationCamera) {
  87353. this._vrDeviceOrientationCamera.position = this._position;
  87354. if (this._scene.activeCamera) {
  87355. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87356. }
  87357. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87358. this._scene.getEngine().switchFullscreen(true);
  87359. this.updateButtonVisibility();
  87360. }
  87361. if (this._scene.activeCamera && this._canvas) {
  87362. this._scene.activeCamera.attachControl(this._canvas);
  87363. }
  87364. if (this._interactionsEnabled) {
  87365. this._scene.registerBeforeRender(this.beforeRender);
  87366. }
  87367. };
  87368. /**
  87369. * Attempt to exit VR, or fullscreen.
  87370. */
  87371. VRExperienceHelper.prototype.exitVR = function () {
  87372. if (this.onExitingVRObservable) {
  87373. try {
  87374. this.onExitingVRObservable.notifyObservers(this);
  87375. }
  87376. catch (err) {
  87377. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  87378. }
  87379. }
  87380. if (this._webVRpresenting) {
  87381. this._scene.getEngine().disableVR();
  87382. }
  87383. if (this._scene.activeCamera) {
  87384. this._position = this._scene.activeCamera.position.clone();
  87385. }
  87386. if (this._deviceOrientationCamera) {
  87387. this._deviceOrientationCamera.position = this._position;
  87388. this._scene.activeCamera = this._deviceOrientationCamera;
  87389. if (this._canvas) {
  87390. this._scene.activeCamera.attachControl(this._canvas);
  87391. }
  87392. }
  87393. else if (this._existingCamera) {
  87394. this._existingCamera.position = this._position;
  87395. this._scene.activeCamera = this._existingCamera;
  87396. }
  87397. this.updateButtonVisibility();
  87398. if (this._interactionsEnabled) {
  87399. this._scene.unregisterBeforeRender(this.beforeRender);
  87400. }
  87401. // resize to update width and height when exiting vr exits fullscreen
  87402. this._scene.getEngine().resize();
  87403. };
  87404. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  87405. /**
  87406. * The position of the vr experience helper.
  87407. */
  87408. get: function () {
  87409. return this._position;
  87410. },
  87411. /**
  87412. * Sets the position of the vr experience helper.
  87413. */
  87414. set: function (value) {
  87415. this._position = value;
  87416. if (this._scene.activeCamera) {
  87417. this._scene.activeCamera.position = value;
  87418. }
  87419. },
  87420. enumerable: true,
  87421. configurable: true
  87422. });
  87423. /**
  87424. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  87425. */
  87426. VRExperienceHelper.prototype.enableInteractions = function () {
  87427. var _this = this;
  87428. if (!this._interactionsEnabled) {
  87429. this._interactionsRequested = true;
  87430. if (this.leftController) {
  87431. this._enableInteractionOnController(this.leftController);
  87432. }
  87433. if (this.rightController) {
  87434. this._enableInteractionOnController(this.rightController);
  87435. }
  87436. this.raySelectionPredicate = function (mesh) {
  87437. return mesh.isVisible;
  87438. };
  87439. this.meshSelectionPredicate = function (mesh) {
  87440. return true;
  87441. };
  87442. this._raySelectionPredicate = function (mesh) {
  87443. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  87444. && mesh.name.indexOf("teleportationTarget") === -1
  87445. && mesh.name.indexOf("torusTeleportation") === -1
  87446. && mesh.name.indexOf("laserPointer") === -1)) {
  87447. return _this.raySelectionPredicate(mesh);
  87448. }
  87449. return false;
  87450. };
  87451. this._interactionsEnabled = true;
  87452. }
  87453. };
  87454. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  87455. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  87456. if (this._floorMeshesCollection[i].id === mesh.id) {
  87457. return true;
  87458. }
  87459. }
  87460. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  87461. return true;
  87462. }
  87463. return false;
  87464. };
  87465. /**
  87466. * Adds a floor mesh to be used for teleportation.
  87467. * @param floorMesh the mesh to be used for teleportation.
  87468. */
  87469. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  87470. if (!this._floorMeshesCollection) {
  87471. return;
  87472. }
  87473. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  87474. return;
  87475. }
  87476. this._floorMeshesCollection.push(floorMesh);
  87477. };
  87478. /**
  87479. * Removes a floor mesh from being used for teleportation.
  87480. * @param floorMesh the mesh to be removed.
  87481. */
  87482. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  87483. if (!this._floorMeshesCollection) {
  87484. return;
  87485. }
  87486. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  87487. if (meshIndex !== -1) {
  87488. this._floorMeshesCollection.splice(meshIndex, 1);
  87489. }
  87490. };
  87491. /**
  87492. * Enables interactions and teleportation using the VR controllers and gaze.
  87493. * @param vrTeleportationOptions options to modify teleportation behavior.
  87494. */
  87495. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  87496. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  87497. if (!this._teleportationInitialized) {
  87498. this._teleportationRequested = true;
  87499. this.enableInteractions();
  87500. if (vrTeleportationOptions.floorMeshName) {
  87501. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  87502. }
  87503. if (vrTeleportationOptions.floorMeshes) {
  87504. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  87505. }
  87506. if (this.leftController != null) {
  87507. this._enableTeleportationOnController(this.leftController);
  87508. }
  87509. if (this.rightController != null) {
  87510. this._enableTeleportationOnController(this.rightController);
  87511. }
  87512. // Creates an image processing post process for the vignette not relying
  87513. // on the main scene configuration for image processing to reduce setup and spaces
  87514. // (gamma/linear) conflicts.
  87515. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  87516. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87517. imageProcessingConfiguration.vignetteEnabled = true;
  87518. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  87519. this._webVRCamera.detachPostProcess(this._postProcessMove);
  87520. this._teleportationInitialized = true;
  87521. if (this._isDefaultTeleportationTarget) {
  87522. this._createTeleportationCircles();
  87523. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  87524. }
  87525. }
  87526. };
  87527. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  87528. var _this = this;
  87529. var controllerMesh = controller.webVRController.mesh;
  87530. if (controllerMesh) {
  87531. controller._interactionsEnabled = true;
  87532. controller._activatePointer();
  87533. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  87534. // Enabling / disabling laserPointer
  87535. if (_this._displayLaserPointer && stateObject.value === 1) {
  87536. if (controller._activePointer) {
  87537. controller._deactivatePointer();
  87538. }
  87539. else {
  87540. controller._activatePointer();
  87541. }
  87542. if (_this.displayGaze) {
  87543. controller._gazeTracker.isVisible = controller._activePointer;
  87544. }
  87545. }
  87546. });
  87547. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  87548. if (!controller._pointerDownOnMeshAsked) {
  87549. if (stateObject.value > _this._padSensibilityUp) {
  87550. controller._selectionPointerDown();
  87551. }
  87552. }
  87553. else if (stateObject.value < _this._padSensibilityDown) {
  87554. controller._selectionPointerUp();
  87555. }
  87556. });
  87557. }
  87558. };
  87559. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87560. // Dont teleport if another gaze already requested teleportation
  87561. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87562. return;
  87563. }
  87564. if (!gazer._teleportationRequestInitiated) {
  87565. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87566. gazer._activatePointer();
  87567. gazer._teleportationRequestInitiated = true;
  87568. }
  87569. }
  87570. else {
  87571. // Listening to the proper controller values changes to confirm teleportation
  87572. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87573. if (this._teleportActive) {
  87574. this._teleportCamera(this._haloCenter);
  87575. }
  87576. gazer._teleportationRequestInitiated = false;
  87577. }
  87578. }
  87579. };
  87580. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87581. // Only rotate when user is not currently selecting a teleportation location
  87582. if (gazer._teleportationRequestInitiated) {
  87583. return;
  87584. }
  87585. if (!this._rotationLeftAsked) {
  87586. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87587. this._rotationLeftAsked = true;
  87588. if (this._rotationAllowed) {
  87589. this._rotateCamera(false);
  87590. }
  87591. }
  87592. }
  87593. else {
  87594. if (stateObject.x > -this._padSensibilityDown) {
  87595. this._rotationLeftAsked = false;
  87596. }
  87597. }
  87598. if (!this._rotationRightAsked) {
  87599. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87600. this._rotationRightAsked = true;
  87601. if (this._rotationAllowed) {
  87602. this._rotateCamera(true);
  87603. }
  87604. }
  87605. }
  87606. else {
  87607. if (stateObject.x < this._padSensibilityDown) {
  87608. this._rotationRightAsked = false;
  87609. }
  87610. }
  87611. };
  87612. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87613. // Only teleport backwards when user is not currently selecting a teleportation location
  87614. if (gazer._teleportationRequestInitiated) {
  87615. return;
  87616. }
  87617. // Teleport backwards
  87618. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87619. if (!gazer._teleportationBackRequestInitiated) {
  87620. if (!this.currentVRCamera) {
  87621. return;
  87622. }
  87623. // Get rotation and position of the current camera
  87624. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87625. var position = this.currentVRCamera.position;
  87626. // If the camera has device position, use that instead
  87627. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87628. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87629. position = this.currentVRCamera.devicePosition;
  87630. }
  87631. // Get matrix with only the y rotation of the device rotation
  87632. rotation.toEulerAnglesToRef(this._workingVector);
  87633. this._workingVector.z = 0;
  87634. this._workingVector.x = 0;
  87635. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87636. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87637. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87638. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87639. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87640. var ray = new BABYLON.Ray(position, this._workingVector);
  87641. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87642. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87643. this._teleportCamera(hit.pickedPoint);
  87644. }
  87645. gazer._teleportationBackRequestInitiated = true;
  87646. }
  87647. }
  87648. else {
  87649. gazer._teleportationBackRequestInitiated = false;
  87650. }
  87651. };
  87652. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87653. var _this = this;
  87654. var controllerMesh = controller.webVRController.mesh;
  87655. if (controllerMesh) {
  87656. if (!controller._interactionsEnabled) {
  87657. this._enableInteractionOnController(controller);
  87658. }
  87659. controller._interactionsEnabled = true;
  87660. controller._teleportationEnabled = true;
  87661. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87662. controller._dpadPressed = false;
  87663. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87664. controller._dpadPressed = stateObject.pressed;
  87665. if (!controller._dpadPressed) {
  87666. _this._rotationLeftAsked = false;
  87667. _this._rotationRightAsked = false;
  87668. controller._teleportationBackRequestInitiated = false;
  87669. }
  87670. });
  87671. }
  87672. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87673. if (_this.teleportationEnabled) {
  87674. _this._checkTeleportBackwards(stateObject, controller);
  87675. _this._checkTeleportWithRay(stateObject, controller);
  87676. }
  87677. _this._checkRotate(stateObject, controller);
  87678. });
  87679. }
  87680. };
  87681. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87682. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87683. this._teleportationTarget.isPickable = false;
  87684. var length = 512;
  87685. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87686. dynamicTexture.hasAlpha = true;
  87687. var context = dynamicTexture.getContext();
  87688. var centerX = length / 2;
  87689. var centerY = length / 2;
  87690. var radius = 200;
  87691. context.beginPath();
  87692. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87693. context.fillStyle = this._teleportationFillColor;
  87694. context.fill();
  87695. context.lineWidth = 10;
  87696. context.strokeStyle = this._teleportationBorderColor;
  87697. context.stroke();
  87698. context.closePath();
  87699. dynamicTexture.update();
  87700. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87701. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87702. this._teleportationTarget.material = teleportationCircleMaterial;
  87703. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87704. torus.isPickable = false;
  87705. torus.parent = this._teleportationTarget;
  87706. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87707. var keys = [];
  87708. keys.push({
  87709. frame: 0,
  87710. value: 0
  87711. });
  87712. keys.push({
  87713. frame: 30,
  87714. value: 0.4
  87715. });
  87716. keys.push({
  87717. frame: 60,
  87718. value: 0
  87719. });
  87720. animationInnerCircle.setKeys(keys);
  87721. var easingFunction = new BABYLON.SineEase();
  87722. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87723. animationInnerCircle.setEasingFunction(easingFunction);
  87724. torus.animations = [];
  87725. torus.animations.push(animationInnerCircle);
  87726. this._scene.beginAnimation(torus, 0, 60, true);
  87727. this._hideTeleportationTarget();
  87728. };
  87729. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87730. this._teleportActive = true;
  87731. if (this._teleportationInitialized) {
  87732. this._teleportationTarget.isVisible = true;
  87733. if (this._isDefaultTeleportationTarget) {
  87734. this._teleportationTarget.getChildren()[0].isVisible = true;
  87735. }
  87736. }
  87737. };
  87738. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87739. this._teleportActive = false;
  87740. if (this._teleportationInitialized) {
  87741. this._teleportationTarget.isVisible = false;
  87742. if (this._isDefaultTeleportationTarget) {
  87743. this._teleportationTarget.getChildren()[0].isVisible = false;
  87744. }
  87745. }
  87746. };
  87747. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87748. var _this = this;
  87749. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87750. return;
  87751. }
  87752. if (right) {
  87753. this._rotationAngle++;
  87754. }
  87755. else {
  87756. this._rotationAngle--;
  87757. }
  87758. this.currentVRCamera.animations = [];
  87759. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87760. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87761. var animationRotationKeys = [];
  87762. animationRotationKeys.push({
  87763. frame: 0,
  87764. value: this.currentVRCamera.rotationQuaternion
  87765. });
  87766. animationRotationKeys.push({
  87767. frame: 6,
  87768. value: target
  87769. });
  87770. animationRotation.setKeys(animationRotationKeys);
  87771. animationRotation.setEasingFunction(this._circleEase);
  87772. this.currentVRCamera.animations.push(animationRotation);
  87773. this._postProcessMove.animations = [];
  87774. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87775. var vignetteWeightKeys = [];
  87776. vignetteWeightKeys.push({
  87777. frame: 0,
  87778. value: 0
  87779. });
  87780. vignetteWeightKeys.push({
  87781. frame: 3,
  87782. value: 4
  87783. });
  87784. vignetteWeightKeys.push({
  87785. frame: 6,
  87786. value: 0
  87787. });
  87788. animationPP.setKeys(vignetteWeightKeys);
  87789. animationPP.setEasingFunction(this._circleEase);
  87790. this._postProcessMove.animations.push(animationPP);
  87791. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87792. var vignetteStretchKeys = [];
  87793. vignetteStretchKeys.push({
  87794. frame: 0,
  87795. value: 0
  87796. });
  87797. vignetteStretchKeys.push({
  87798. frame: 3,
  87799. value: 10
  87800. });
  87801. vignetteStretchKeys.push({
  87802. frame: 6,
  87803. value: 0
  87804. });
  87805. animationPP2.setKeys(vignetteStretchKeys);
  87806. animationPP2.setEasingFunction(this._circleEase);
  87807. this._postProcessMove.animations.push(animationPP2);
  87808. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87809. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87810. this._postProcessMove.samples = 4;
  87811. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87812. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87813. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87814. });
  87815. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87816. };
  87817. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87818. if (hit.pickedPoint) {
  87819. if (gazer._teleportationRequestInitiated) {
  87820. this._displayTeleportationTarget();
  87821. this._haloCenter.copyFrom(hit.pickedPoint);
  87822. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87823. }
  87824. var pickNormal = hit.getNormal(true, false);
  87825. if (pickNormal) {
  87826. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87827. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87828. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87829. }
  87830. this._teleportationTarget.position.y += 0.1;
  87831. }
  87832. };
  87833. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87834. var _this = this;
  87835. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87836. return;
  87837. }
  87838. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  87839. // offset of the headset from the anchor.
  87840. if (this.webVRCamera.leftCamera) {
  87841. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  87842. this._workingVector.subtractInPlace(this.webVRCamera.position);
  87843. location.subtractToRef(this._workingVector, this._workingVector);
  87844. }
  87845. else {
  87846. this._workingVector.copyFrom(location);
  87847. }
  87848. // Add height to account for user's height offset
  87849. if (this.isInVRMode) {
  87850. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  87851. }
  87852. else {
  87853. this._workingVector.y += this._defaultHeight;
  87854. }
  87855. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  87856. // Create animation from the camera's position to the new location
  87857. this.currentVRCamera.animations = [];
  87858. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87859. var animationCameraTeleportationKeys = [{
  87860. frame: 0,
  87861. value: this.currentVRCamera.position
  87862. },
  87863. {
  87864. frame: 11,
  87865. value: this._workingVector
  87866. }
  87867. ];
  87868. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  87869. animationCameraTeleportation.setEasingFunction(this._circleEase);
  87870. this.currentVRCamera.animations.push(animationCameraTeleportation);
  87871. this._postProcessMove.animations = [];
  87872. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87873. var vignetteWeightKeys = [];
  87874. vignetteWeightKeys.push({
  87875. frame: 0,
  87876. value: 0
  87877. });
  87878. vignetteWeightKeys.push({
  87879. frame: 5,
  87880. value: 8
  87881. });
  87882. vignetteWeightKeys.push({
  87883. frame: 11,
  87884. value: 0
  87885. });
  87886. animationPP.setKeys(vignetteWeightKeys);
  87887. this._postProcessMove.animations.push(animationPP);
  87888. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87889. var vignetteStretchKeys = [];
  87890. vignetteStretchKeys.push({
  87891. frame: 0,
  87892. value: 0
  87893. });
  87894. vignetteStretchKeys.push({
  87895. frame: 5,
  87896. value: 10
  87897. });
  87898. vignetteStretchKeys.push({
  87899. frame: 11,
  87900. value: 0
  87901. });
  87902. animationPP2.setKeys(vignetteStretchKeys);
  87903. this._postProcessMove.animations.push(animationPP2);
  87904. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87905. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87906. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87907. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  87908. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87909. });
  87910. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  87911. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  87912. });
  87913. this._hideTeleportationTarget();
  87914. };
  87915. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  87916. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87917. return;
  87918. }
  87919. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  87920. // Moving the gazeTracker on the mesh face targetted
  87921. if (hit && hit.pickedPoint) {
  87922. if (this._displayGaze) {
  87923. var multiplier = 1;
  87924. gazer._gazeTracker.isVisible = true;
  87925. if (gazer._isActionableMesh) {
  87926. multiplier = 3;
  87927. }
  87928. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  87929. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  87930. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  87931. var pickNormal = hit.getNormal();
  87932. // To avoid z-fighting
  87933. var deltaFighting = 0.002;
  87934. if (pickNormal) {
  87935. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87936. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87937. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  87938. }
  87939. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  87940. if (gazer._gazeTracker.position.x < 0) {
  87941. gazer._gazeTracker.position.x += deltaFighting;
  87942. }
  87943. else {
  87944. gazer._gazeTracker.position.x -= deltaFighting;
  87945. }
  87946. if (gazer._gazeTracker.position.y < 0) {
  87947. gazer._gazeTracker.position.y += deltaFighting;
  87948. }
  87949. else {
  87950. gazer._gazeTracker.position.y -= deltaFighting;
  87951. }
  87952. if (gazer._gazeTracker.position.z < 0) {
  87953. gazer._gazeTracker.position.z += deltaFighting;
  87954. }
  87955. else {
  87956. gazer._gazeTracker.position.z -= deltaFighting;
  87957. }
  87958. }
  87959. // Changing the size of the laser pointer based on the distance from the targetted point
  87960. gazer._updatePointerDistance(hit.distance);
  87961. }
  87962. else {
  87963. gazer._gazeTracker.isVisible = false;
  87964. }
  87965. if (hit && hit.pickedMesh) {
  87966. gazer._currentHit = hit;
  87967. if (gazer._pointerDownOnMeshAsked) {
  87968. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  87969. }
  87970. // The object selected is the floor, we're in a teleportation scenario
  87971. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  87972. // Moving the teleportation area to this targetted point
  87973. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  87974. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  87975. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  87976. }
  87977. gazer._currentMeshSelected = null;
  87978. if (gazer._teleportationRequestInitiated) {
  87979. this._moveTeleportationSelectorTo(hit, gazer);
  87980. }
  87981. return;
  87982. }
  87983. // If not, we're in a selection scenario
  87984. //this._teleportationAllowed = false;
  87985. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  87986. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  87987. this.onNewMeshPicked.notifyObservers(hit);
  87988. gazer._currentMeshSelected = hit.pickedMesh;
  87989. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  87990. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  87991. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  87992. gazer._isActionableMesh = true;
  87993. }
  87994. else {
  87995. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87996. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  87997. gazer._isActionableMesh = false;
  87998. }
  87999. try {
  88000. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88001. }
  88002. catch (err) {
  88003. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88004. }
  88005. }
  88006. else {
  88007. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88008. gazer._currentMeshSelected = null;
  88009. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88010. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88011. }
  88012. }
  88013. }
  88014. else {
  88015. gazer._currentHit = null;
  88016. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88017. gazer._currentMeshSelected = null;
  88018. //this._teleportationAllowed = false;
  88019. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88020. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88021. }
  88022. };
  88023. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88024. if (mesh) {
  88025. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88026. }
  88027. };
  88028. /**
  88029. * Sets the color of the laser ray from the vr controllers.
  88030. * @param color new color for the ray.
  88031. */
  88032. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88033. if (this.leftController) {
  88034. this.leftController._setLaserPointerColor(color);
  88035. }
  88036. if (this.rightController) {
  88037. this.rightController._setLaserPointerColor(color);
  88038. }
  88039. };
  88040. /**
  88041. * Sets the color of the ray from the vr headsets gaze.
  88042. * @param color new color for the ray.
  88043. */
  88044. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88045. if (!this._cameraGazer._gazeTracker.material) {
  88046. return;
  88047. }
  88048. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88049. if (this.leftController) {
  88050. this.leftController._gazeTracker.material.emissiveColor = color;
  88051. }
  88052. if (this.rightController) {
  88053. this.rightController._gazeTracker.material.emissiveColor = color;
  88054. }
  88055. };
  88056. /**
  88057. * Exits VR and disposes of the vr experience helper
  88058. */
  88059. VRExperienceHelper.prototype.dispose = function () {
  88060. if (this.isInVRMode) {
  88061. this.exitVR();
  88062. }
  88063. if (this._postProcessMove) {
  88064. this._postProcessMove.dispose();
  88065. }
  88066. if (this._webVRCamera) {
  88067. this._webVRCamera.dispose();
  88068. }
  88069. if (this._vrDeviceOrientationCamera) {
  88070. this._vrDeviceOrientationCamera.dispose();
  88071. }
  88072. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88073. document.body.removeChild(this._btnVR);
  88074. }
  88075. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88076. this._deviceOrientationCamera.dispose();
  88077. }
  88078. if (this._cameraGazer) {
  88079. this._cameraGazer.dispose();
  88080. }
  88081. if (this.leftController) {
  88082. this.leftController.dispose();
  88083. }
  88084. if (this.rightController) {
  88085. this.rightController.dispose();
  88086. }
  88087. if (this._teleportationTarget) {
  88088. this._teleportationTarget.dispose();
  88089. }
  88090. this._floorMeshesCollection = [];
  88091. document.removeEventListener("keydown", this._onKeyDown);
  88092. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88093. window.removeEventListener("resize", this._onResize);
  88094. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88095. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88096. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88097. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88098. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88099. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88100. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88101. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88102. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88103. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88104. this._scene.unregisterBeforeRender(this.beforeRender);
  88105. };
  88106. /**
  88107. * Gets the name of the VRExperienceHelper class
  88108. * @returns "VRExperienceHelper"
  88109. */
  88110. VRExperienceHelper.prototype.getClassName = function () {
  88111. return "VRExperienceHelper";
  88112. };
  88113. return VRExperienceHelper;
  88114. }());
  88115. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88116. })(BABYLON || (BABYLON = {}));
  88117. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88118. // Mainly based on these 2 articles :
  88119. // 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
  88120. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88121. var BABYLON;
  88122. (function (BABYLON) {
  88123. var JoystickAxis;
  88124. (function (JoystickAxis) {
  88125. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88126. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88127. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88128. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88129. var VirtualJoystick = /** @class */ (function () {
  88130. function VirtualJoystick(leftJoystick) {
  88131. var _this = this;
  88132. if (leftJoystick) {
  88133. this._leftJoystick = true;
  88134. }
  88135. else {
  88136. this._leftJoystick = false;
  88137. }
  88138. VirtualJoystick._globalJoystickIndex++;
  88139. // By default left & right arrow keys are moving the X
  88140. // and up & down keys are moving the Y
  88141. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88142. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88143. this.reverseLeftRight = false;
  88144. this.reverseUpDown = false;
  88145. // collections of pointers
  88146. this._touches = new BABYLON.StringDictionary();
  88147. this.deltaPosition = BABYLON.Vector3.Zero();
  88148. this._joystickSensibility = 25;
  88149. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88150. this._onResize = function (evt) {
  88151. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88152. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88153. if (VirtualJoystick.vjCanvas) {
  88154. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88155. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88156. }
  88157. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88158. };
  88159. // injecting a canvas element on top of the canvas 3D game
  88160. if (!VirtualJoystick.vjCanvas) {
  88161. window.addEventListener("resize", this._onResize, false);
  88162. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88163. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88164. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88165. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88166. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88167. VirtualJoystick.vjCanvas.style.width = "100%";
  88168. VirtualJoystick.vjCanvas.style.height = "100%";
  88169. VirtualJoystick.vjCanvas.style.position = "absolute";
  88170. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88171. VirtualJoystick.vjCanvas.style.top = "0px";
  88172. VirtualJoystick.vjCanvas.style.left = "0px";
  88173. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88174. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88175. // Support for jQuery PEP polyfill
  88176. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88177. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88178. if (!context) {
  88179. throw new Error("Unable to create canvas for virtual joystick");
  88180. }
  88181. VirtualJoystick.vjCanvasContext = context;
  88182. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88183. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88184. document.body.appendChild(VirtualJoystick.vjCanvas);
  88185. }
  88186. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88187. this.pressed = false;
  88188. // default joystick color
  88189. this._joystickColor = "cyan";
  88190. this._joystickPointerID = -1;
  88191. // current joystick position
  88192. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88193. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88194. // origin joystick position
  88195. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88196. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88197. this._onPointerDownHandlerRef = function (evt) {
  88198. _this._onPointerDown(evt);
  88199. };
  88200. this._onPointerMoveHandlerRef = function (evt) {
  88201. _this._onPointerMove(evt);
  88202. };
  88203. this._onPointerUpHandlerRef = function (evt) {
  88204. _this._onPointerUp(evt);
  88205. };
  88206. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88207. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88208. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88209. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88210. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88211. evt.preventDefault(); // Disables system menu
  88212. }, false);
  88213. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88214. }
  88215. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88216. this._joystickSensibility = newJoystickSensibility;
  88217. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88218. };
  88219. VirtualJoystick.prototype._onPointerDown = function (e) {
  88220. var positionOnScreenCondition;
  88221. e.preventDefault();
  88222. if (this._leftJoystick === true) {
  88223. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88224. }
  88225. else {
  88226. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88227. }
  88228. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88229. // First contact will be dedicated to the virtual joystick
  88230. this._joystickPointerID = e.pointerId;
  88231. this._joystickPointerStartPos.x = e.clientX;
  88232. this._joystickPointerStartPos.y = e.clientY;
  88233. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88234. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88235. this._deltaJoystickVector.x = 0;
  88236. this._deltaJoystickVector.y = 0;
  88237. this.pressed = true;
  88238. this._touches.add(e.pointerId.toString(), e);
  88239. }
  88240. else {
  88241. // You can only trigger the action buttons with a joystick declared
  88242. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88243. this._action();
  88244. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88245. }
  88246. }
  88247. };
  88248. VirtualJoystick.prototype._onPointerMove = function (e) {
  88249. // If the current pointer is the one associated to the joystick (first touch contact)
  88250. if (this._joystickPointerID == e.pointerId) {
  88251. this._joystickPointerPos.x = e.clientX;
  88252. this._joystickPointerPos.y = e.clientY;
  88253. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88254. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88255. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88256. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88257. switch (this._axisTargetedByLeftAndRight) {
  88258. case JoystickAxis.X:
  88259. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88260. break;
  88261. case JoystickAxis.Y:
  88262. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88263. break;
  88264. case JoystickAxis.Z:
  88265. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88266. break;
  88267. }
  88268. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88269. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88270. switch (this._axisTargetedByUpAndDown) {
  88271. case JoystickAxis.X:
  88272. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88273. break;
  88274. case JoystickAxis.Y:
  88275. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88276. break;
  88277. case JoystickAxis.Z:
  88278. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88279. break;
  88280. }
  88281. }
  88282. else {
  88283. var data = this._touches.get(e.pointerId.toString());
  88284. if (data) {
  88285. data.x = e.clientX;
  88286. data.y = e.clientY;
  88287. }
  88288. }
  88289. };
  88290. VirtualJoystick.prototype._onPointerUp = function (e) {
  88291. if (this._joystickPointerID == e.pointerId) {
  88292. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88293. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88294. this._joystickPointerID = -1;
  88295. this.pressed = false;
  88296. }
  88297. else {
  88298. var touch = this._touches.get(e.pointerId.toString());
  88299. if (touch) {
  88300. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88301. }
  88302. }
  88303. this._deltaJoystickVector.x = 0;
  88304. this._deltaJoystickVector.y = 0;
  88305. this._touches.remove(e.pointerId.toString());
  88306. };
  88307. /**
  88308. * Change the color of the virtual joystick
  88309. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88310. */
  88311. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88312. this._joystickColor = newColor;
  88313. };
  88314. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88315. this._action = action;
  88316. };
  88317. // Define which axis you'd like to control for left & right
  88318. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88319. switch (axis) {
  88320. case JoystickAxis.X:
  88321. case JoystickAxis.Y:
  88322. case JoystickAxis.Z:
  88323. this._axisTargetedByLeftAndRight = axis;
  88324. break;
  88325. default:
  88326. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88327. break;
  88328. }
  88329. };
  88330. // Define which axis you'd like to control for up & down
  88331. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  88332. switch (axis) {
  88333. case JoystickAxis.X:
  88334. case JoystickAxis.Y:
  88335. case JoystickAxis.Z:
  88336. this._axisTargetedByUpAndDown = axis;
  88337. break;
  88338. default:
  88339. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88340. break;
  88341. }
  88342. };
  88343. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  88344. var _this = this;
  88345. if (this.pressed) {
  88346. this._touches.forEach(function (key, touch) {
  88347. if (touch.pointerId === _this._joystickPointerID) {
  88348. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  88349. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  88350. VirtualJoystick.vjCanvasContext.beginPath();
  88351. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88352. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88353. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  88354. VirtualJoystick.vjCanvasContext.stroke();
  88355. VirtualJoystick.vjCanvasContext.closePath();
  88356. VirtualJoystick.vjCanvasContext.beginPath();
  88357. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88358. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88359. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  88360. VirtualJoystick.vjCanvasContext.stroke();
  88361. VirtualJoystick.vjCanvasContext.closePath();
  88362. VirtualJoystick.vjCanvasContext.beginPath();
  88363. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88364. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  88365. VirtualJoystick.vjCanvasContext.stroke();
  88366. VirtualJoystick.vjCanvasContext.closePath();
  88367. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  88368. }
  88369. else {
  88370. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88371. VirtualJoystick.vjCanvasContext.beginPath();
  88372. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  88373. VirtualJoystick.vjCanvasContext.beginPath();
  88374. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  88375. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88376. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  88377. VirtualJoystick.vjCanvasContext.stroke();
  88378. VirtualJoystick.vjCanvasContext.closePath();
  88379. touch.prevX = touch.x;
  88380. touch.prevY = touch.y;
  88381. }
  88382. ;
  88383. });
  88384. }
  88385. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88386. };
  88387. VirtualJoystick.prototype.releaseCanvas = function () {
  88388. if (VirtualJoystick.vjCanvas) {
  88389. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  88390. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  88391. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  88392. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  88393. window.removeEventListener("resize", this._onResize);
  88394. document.body.removeChild(VirtualJoystick.vjCanvas);
  88395. VirtualJoystick.vjCanvas = null;
  88396. }
  88397. };
  88398. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  88399. VirtualJoystick._globalJoystickIndex = 0;
  88400. return VirtualJoystick;
  88401. }());
  88402. BABYLON.VirtualJoystick = VirtualJoystick;
  88403. })(BABYLON || (BABYLON = {}));
  88404. //# sourceMappingURL=babylon.virtualJoystick.js.map
  88405. var BABYLON;
  88406. (function (BABYLON) {
  88407. // We're mainly based on the logic defined into the FreeCamera code
  88408. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  88409. __extends(VirtualJoysticksCamera, _super);
  88410. function VirtualJoysticksCamera(name, position, scene) {
  88411. var _this = _super.call(this, name, position, scene) || this;
  88412. _this.inputs.addVirtualJoystick();
  88413. return _this;
  88414. }
  88415. VirtualJoysticksCamera.prototype.getClassName = function () {
  88416. return "VirtualJoysticksCamera";
  88417. };
  88418. return VirtualJoysticksCamera;
  88419. }(BABYLON.FreeCamera));
  88420. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  88421. })(BABYLON || (BABYLON = {}));
  88422. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  88423. var BABYLON;
  88424. (function (BABYLON) {
  88425. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  88426. function FreeCameraVirtualJoystickInput() {
  88427. }
  88428. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  88429. return this._leftjoystick;
  88430. };
  88431. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  88432. return this._rightjoystick;
  88433. };
  88434. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  88435. if (this._leftjoystick) {
  88436. var camera = this.camera;
  88437. var speed = camera._computeLocalCameraSpeed() * 50;
  88438. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  88439. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  88440. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  88441. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  88442. if (!this._leftjoystick.pressed) {
  88443. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  88444. }
  88445. if (!this._rightjoystick.pressed) {
  88446. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  88447. }
  88448. }
  88449. };
  88450. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  88451. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  88452. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  88453. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  88454. this._leftjoystick.setJoystickSensibility(0.15);
  88455. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  88456. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  88457. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  88458. this._rightjoystick.reverseUpDown = true;
  88459. this._rightjoystick.setJoystickSensibility(0.05);
  88460. this._rightjoystick.setJoystickColor("yellow");
  88461. };
  88462. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  88463. this._leftjoystick.releaseCanvas();
  88464. this._rightjoystick.releaseCanvas();
  88465. };
  88466. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  88467. return "FreeCameraVirtualJoystickInput";
  88468. };
  88469. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  88470. return "virtualJoystick";
  88471. };
  88472. return FreeCameraVirtualJoystickInput;
  88473. }());
  88474. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  88475. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  88476. })(BABYLON || (BABYLON = {}));
  88477. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  88478. var BABYLON;
  88479. (function (BABYLON) {
  88480. var SimplificationSettings = /** @class */ (function () {
  88481. function SimplificationSettings(quality, distance, optimizeMesh) {
  88482. this.quality = quality;
  88483. this.distance = distance;
  88484. this.optimizeMesh = optimizeMesh;
  88485. }
  88486. return SimplificationSettings;
  88487. }());
  88488. BABYLON.SimplificationSettings = SimplificationSettings;
  88489. var SimplificationQueue = /** @class */ (function () {
  88490. function SimplificationQueue() {
  88491. this.running = false;
  88492. this._simplificationArray = [];
  88493. }
  88494. SimplificationQueue.prototype.addTask = function (task) {
  88495. this._simplificationArray.push(task);
  88496. };
  88497. SimplificationQueue.prototype.executeNext = function () {
  88498. var task = this._simplificationArray.pop();
  88499. if (task) {
  88500. this.running = true;
  88501. this.runSimplification(task);
  88502. }
  88503. else {
  88504. this.running = false;
  88505. }
  88506. };
  88507. SimplificationQueue.prototype.runSimplification = function (task) {
  88508. var _this = this;
  88509. if (task.parallelProcessing) {
  88510. //parallel simplifier
  88511. task.settings.forEach(function (setting) {
  88512. var simplifier = _this.getSimplifier(task);
  88513. simplifier.simplify(setting, function (newMesh) {
  88514. task.mesh.addLODLevel(setting.distance, newMesh);
  88515. newMesh.isVisible = true;
  88516. //check if it is the last
  88517. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  88518. //all done, run the success callback.
  88519. task.successCallback();
  88520. }
  88521. _this.executeNext();
  88522. });
  88523. });
  88524. }
  88525. else {
  88526. //single simplifier.
  88527. var simplifier = this.getSimplifier(task);
  88528. var runDecimation = function (setting, callback) {
  88529. simplifier.simplify(setting, function (newMesh) {
  88530. task.mesh.addLODLevel(setting.distance, newMesh);
  88531. newMesh.isVisible = true;
  88532. //run the next quality level
  88533. callback();
  88534. });
  88535. };
  88536. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  88537. runDecimation(task.settings[loop.index], function () {
  88538. loop.executeNext();
  88539. });
  88540. }, function () {
  88541. //execution ended, run the success callback.
  88542. if (task.successCallback) {
  88543. task.successCallback();
  88544. }
  88545. _this.executeNext();
  88546. });
  88547. }
  88548. };
  88549. SimplificationQueue.prototype.getSimplifier = function (task) {
  88550. switch (task.simplificationType) {
  88551. case SimplificationType.QUADRATIC:
  88552. default:
  88553. return new QuadraticErrorSimplification(task.mesh);
  88554. }
  88555. };
  88556. return SimplificationQueue;
  88557. }());
  88558. BABYLON.SimplificationQueue = SimplificationQueue;
  88559. /**
  88560. * The implemented types of simplification.
  88561. * At the moment only Quadratic Error Decimation is implemented.
  88562. */
  88563. var SimplificationType;
  88564. (function (SimplificationType) {
  88565. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88566. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88567. var DecimationTriangle = /** @class */ (function () {
  88568. function DecimationTriangle(vertices) {
  88569. this.vertices = vertices;
  88570. this.error = new Array(4);
  88571. this.deleted = false;
  88572. this.isDirty = false;
  88573. this.deletePending = false;
  88574. this.borderFactor = 0;
  88575. }
  88576. return DecimationTriangle;
  88577. }());
  88578. BABYLON.DecimationTriangle = DecimationTriangle;
  88579. var DecimationVertex = /** @class */ (function () {
  88580. function DecimationVertex(position, id) {
  88581. this.position = position;
  88582. this.id = id;
  88583. this.isBorder = true;
  88584. this.q = new QuadraticMatrix();
  88585. this.triangleCount = 0;
  88586. this.triangleStart = 0;
  88587. this.originalOffsets = [];
  88588. }
  88589. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88590. this.position.copyFrom(newPosition);
  88591. };
  88592. return DecimationVertex;
  88593. }());
  88594. BABYLON.DecimationVertex = DecimationVertex;
  88595. var QuadraticMatrix = /** @class */ (function () {
  88596. function QuadraticMatrix(data) {
  88597. this.data = new Array(10);
  88598. for (var i = 0; i < 10; ++i) {
  88599. if (data && data[i]) {
  88600. this.data[i] = data[i];
  88601. }
  88602. else {
  88603. this.data[i] = 0;
  88604. }
  88605. }
  88606. }
  88607. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88608. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88609. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88610. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88611. return det;
  88612. };
  88613. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88614. for (var i = 0; i < 10; ++i) {
  88615. this.data[i] += matrix.data[i];
  88616. }
  88617. };
  88618. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88619. for (var i = 0; i < 10; ++i) {
  88620. this.data[i] += data[i];
  88621. }
  88622. };
  88623. QuadraticMatrix.prototype.add = function (matrix) {
  88624. var m = new QuadraticMatrix();
  88625. for (var i = 0; i < 10; ++i) {
  88626. m.data[i] = this.data[i] + matrix.data[i];
  88627. }
  88628. return m;
  88629. };
  88630. QuadraticMatrix.FromData = function (a, b, c, d) {
  88631. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88632. };
  88633. //returning an array to avoid garbage collection
  88634. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88635. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88636. };
  88637. return QuadraticMatrix;
  88638. }());
  88639. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88640. var Reference = /** @class */ (function () {
  88641. function Reference(vertexId, triangleId) {
  88642. this.vertexId = vertexId;
  88643. this.triangleId = triangleId;
  88644. }
  88645. return Reference;
  88646. }());
  88647. BABYLON.Reference = Reference;
  88648. /**
  88649. * An implementation of the Quadratic Error simplification algorithm.
  88650. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88651. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88652. * @author RaananW
  88653. */
  88654. var QuadraticErrorSimplification = /** @class */ (function () {
  88655. function QuadraticErrorSimplification(_mesh) {
  88656. this._mesh = _mesh;
  88657. this.syncIterations = 5000;
  88658. this.aggressiveness = 7;
  88659. this.decimationIterations = 100;
  88660. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88661. }
  88662. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88663. var _this = this;
  88664. this.initDecimatedMesh();
  88665. //iterating through the submeshes array, one after the other.
  88666. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88667. _this.initWithMesh(loop.index, function () {
  88668. _this.runDecimation(settings, loop.index, function () {
  88669. loop.executeNext();
  88670. });
  88671. }, settings.optimizeMesh);
  88672. }, function () {
  88673. setTimeout(function () {
  88674. successCallback(_this._reconstructedMesh);
  88675. }, 0);
  88676. });
  88677. };
  88678. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88679. var _this = this;
  88680. var targetCount = ~~(this.triangles.length * settings.quality);
  88681. var deletedTriangles = 0;
  88682. var triangleCount = this.triangles.length;
  88683. var iterationFunction = function (iteration, callback) {
  88684. setTimeout(function () {
  88685. if (iteration % 5 === 0) {
  88686. _this.updateMesh(iteration === 0);
  88687. }
  88688. for (var i = 0; i < _this.triangles.length; ++i) {
  88689. _this.triangles[i].isDirty = false;
  88690. }
  88691. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88692. var trianglesIterator = function (i) {
  88693. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88694. var t = _this.triangles[tIdx];
  88695. if (!t)
  88696. return;
  88697. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88698. return;
  88699. }
  88700. for (var j = 0; j < 3; ++j) {
  88701. if (t.error[j] < threshold) {
  88702. var deleted0 = [];
  88703. var deleted1 = [];
  88704. var v0 = t.vertices[j];
  88705. var v1 = t.vertices[(j + 1) % 3];
  88706. if (v0.isBorder || v1.isBorder)
  88707. continue;
  88708. var p = BABYLON.Vector3.Zero();
  88709. var n = BABYLON.Vector3.Zero();
  88710. var uv = BABYLON.Vector2.Zero();
  88711. var color = new BABYLON.Color4(0, 0, 0, 1);
  88712. _this.calculateError(v0, v1, p, n, uv, color);
  88713. var delTr = new Array();
  88714. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88715. continue;
  88716. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88717. continue;
  88718. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88719. continue;
  88720. var uniqueArray = new Array();
  88721. delTr.forEach(function (deletedT) {
  88722. if (uniqueArray.indexOf(deletedT) === -1) {
  88723. deletedT.deletePending = true;
  88724. uniqueArray.push(deletedT);
  88725. }
  88726. });
  88727. if (uniqueArray.length % 2 !== 0) {
  88728. continue;
  88729. }
  88730. v0.q = v1.q.add(v0.q);
  88731. v0.updatePosition(p);
  88732. var tStart = _this.references.length;
  88733. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88734. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88735. var tCount = _this.references.length - tStart;
  88736. if (tCount <= v0.triangleCount) {
  88737. if (tCount) {
  88738. for (var c = 0; c < tCount; c++) {
  88739. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88740. }
  88741. }
  88742. }
  88743. else {
  88744. v0.triangleStart = tStart;
  88745. }
  88746. v0.triangleCount = tCount;
  88747. break;
  88748. }
  88749. }
  88750. };
  88751. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88752. }, 0);
  88753. };
  88754. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88755. if (triangleCount - deletedTriangles <= targetCount)
  88756. loop.breakLoop();
  88757. else {
  88758. iterationFunction(loop.index, function () {
  88759. loop.executeNext();
  88760. });
  88761. }
  88762. }, function () {
  88763. setTimeout(function () {
  88764. //reconstruct this part of the mesh
  88765. _this.reconstructMesh(submeshIndex);
  88766. successCallback();
  88767. }, 0);
  88768. });
  88769. };
  88770. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88771. var _this = this;
  88772. this.vertices = [];
  88773. this.triangles = [];
  88774. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88775. var indices = this._mesh.getIndices();
  88776. var submesh = this._mesh.subMeshes[submeshIndex];
  88777. var findInVertices = function (positionToSearch) {
  88778. if (optimizeMesh) {
  88779. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88780. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88781. return _this.vertices[ii];
  88782. }
  88783. }
  88784. }
  88785. return null;
  88786. };
  88787. var vertexReferences = [];
  88788. var vertexInit = function (i) {
  88789. if (!positionData) {
  88790. return;
  88791. }
  88792. var offset = i + submesh.verticesStart;
  88793. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88794. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88795. vertex.originalOffsets.push(offset);
  88796. if (vertex.id === _this.vertices.length) {
  88797. _this.vertices.push(vertex);
  88798. }
  88799. vertexReferences.push(vertex.id);
  88800. };
  88801. //var totalVertices = mesh.getTotalVertices();
  88802. var totalVertices = submesh.verticesCount;
  88803. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88804. var indicesInit = function (i) {
  88805. if (!indices) {
  88806. return;
  88807. }
  88808. var offset = (submesh.indexStart / 3) + i;
  88809. var pos = (offset * 3);
  88810. var i0 = indices[pos + 0];
  88811. var i1 = indices[pos + 1];
  88812. var i2 = indices[pos + 2];
  88813. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  88814. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  88815. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  88816. var triangle = new DecimationTriangle([v0, v1, v2]);
  88817. triangle.originalOffset = pos;
  88818. _this.triangles.push(triangle);
  88819. };
  88820. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  88821. _this.init(callback);
  88822. });
  88823. });
  88824. };
  88825. QuadraticErrorSimplification.prototype.init = function (callback) {
  88826. var _this = this;
  88827. var triangleInit1 = function (i) {
  88828. var t = _this.triangles[i];
  88829. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  88830. for (var j = 0; j < 3; j++) {
  88831. 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))));
  88832. }
  88833. };
  88834. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  88835. var triangleInit2 = function (i) {
  88836. var t = _this.triangles[i];
  88837. for (var j = 0; j < 3; ++j) {
  88838. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  88839. }
  88840. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88841. };
  88842. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  88843. callback();
  88844. });
  88845. });
  88846. };
  88847. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  88848. var newTriangles = [];
  88849. var i;
  88850. for (i = 0; i < this.vertices.length; ++i) {
  88851. this.vertices[i].triangleCount = 0;
  88852. }
  88853. var t;
  88854. var j;
  88855. for (i = 0; i < this.triangles.length; ++i) {
  88856. if (!this.triangles[i].deleted) {
  88857. t = this.triangles[i];
  88858. for (j = 0; j < 3; ++j) {
  88859. t.vertices[j].triangleCount = 1;
  88860. }
  88861. newTriangles.push(t);
  88862. }
  88863. }
  88864. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  88865. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  88866. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  88867. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  88868. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  88869. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  88870. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  88871. var vertexCount = 0;
  88872. for (i = 0; i < this.vertices.length; ++i) {
  88873. var vertex = this.vertices[i];
  88874. vertex.id = vertexCount;
  88875. if (vertex.triangleCount) {
  88876. vertex.originalOffsets.forEach(function (originalOffset) {
  88877. if (!normalData) {
  88878. return;
  88879. }
  88880. newPositionData.push(vertex.position.x);
  88881. newPositionData.push(vertex.position.y);
  88882. newPositionData.push(vertex.position.z);
  88883. newNormalData.push(normalData[originalOffset * 3]);
  88884. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  88885. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  88886. if (uvs && uvs.length) {
  88887. newUVsData.push(uvs[(originalOffset * 2)]);
  88888. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  88889. }
  88890. else if (colorsData && colorsData.length) {
  88891. newColorsData.push(colorsData[(originalOffset * 4)]);
  88892. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  88893. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  88894. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  88895. }
  88896. ++vertexCount;
  88897. });
  88898. }
  88899. }
  88900. var startingIndex = this._reconstructedMesh.getTotalIndices();
  88901. var startingVertex = this._reconstructedMesh.getTotalVertices();
  88902. var submeshesArray = this._reconstructedMesh.subMeshes;
  88903. this._reconstructedMesh.subMeshes = [];
  88904. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  88905. var originalIndices = this._mesh.getIndices();
  88906. for (i = 0; i < newTriangles.length; ++i) {
  88907. t = newTriangles[i]; //now get the new referencing point for each vertex
  88908. [0, 1, 2].forEach(function (idx) {
  88909. var id = originalIndices[t.originalOffset + idx];
  88910. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  88911. if (offset < 0)
  88912. offset = 0;
  88913. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  88914. });
  88915. }
  88916. //overwriting the old vertex buffers and indices.
  88917. this._reconstructedMesh.setIndices(newIndicesArray);
  88918. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  88919. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  88920. if (newUVsData.length > 0)
  88921. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  88922. if (newColorsData.length > 0)
  88923. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  88924. //create submesh
  88925. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  88926. if (submeshIndex > 0) {
  88927. this._reconstructedMesh.subMeshes = [];
  88928. submeshesArray.forEach(function (submesh) {
  88929. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  88930. });
  88931. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  88932. }
  88933. };
  88934. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  88935. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  88936. this._reconstructedMesh.material = this._mesh.material;
  88937. this._reconstructedMesh.parent = this._mesh.parent;
  88938. this._reconstructedMesh.isVisible = false;
  88939. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  88940. };
  88941. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  88942. for (var i = 0; i < vertex1.triangleCount; ++i) {
  88943. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  88944. if (t.deleted)
  88945. continue;
  88946. var s = this.references[vertex1.triangleStart + i].vertexId;
  88947. var v1 = t.vertices[(s + 1) % 3];
  88948. var v2 = t.vertices[(s + 2) % 3];
  88949. if ((v1 === vertex2 || v2 === vertex2)) {
  88950. deletedArray[i] = true;
  88951. delTr.push(t);
  88952. continue;
  88953. }
  88954. var d1 = v1.position.subtract(point);
  88955. d1 = d1.normalize();
  88956. var d2 = v2.position.subtract(point);
  88957. d2 = d2.normalize();
  88958. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  88959. return true;
  88960. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  88961. deletedArray[i] = false;
  88962. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  88963. return true;
  88964. }
  88965. return false;
  88966. };
  88967. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  88968. var newDeleted = deletedTriangles;
  88969. for (var i = 0; i < vertex.triangleCount; ++i) {
  88970. var ref = this.references[vertex.triangleStart + i];
  88971. var t = this.triangles[ref.triangleId];
  88972. if (t.deleted)
  88973. continue;
  88974. if (deletedArray[i] && t.deletePending) {
  88975. t.deleted = true;
  88976. newDeleted++;
  88977. continue;
  88978. }
  88979. t.vertices[ref.vertexId] = origVertex;
  88980. t.isDirty = true;
  88981. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  88982. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  88983. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  88984. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  88985. this.references.push(ref);
  88986. }
  88987. return newDeleted;
  88988. };
  88989. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  88990. for (var i = 0; i < this.vertices.length; ++i) {
  88991. var vCount = [];
  88992. var vId = [];
  88993. var v = this.vertices[i];
  88994. var j;
  88995. for (j = 0; j < v.triangleCount; ++j) {
  88996. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  88997. for (var ii = 0; ii < 3; ii++) {
  88998. var ofs = 0;
  88999. var vv = triangle.vertices[ii];
  89000. while (ofs < vCount.length) {
  89001. if (vId[ofs] === vv.id)
  89002. break;
  89003. ++ofs;
  89004. }
  89005. if (ofs === vCount.length) {
  89006. vCount.push(1);
  89007. vId.push(vv.id);
  89008. }
  89009. else {
  89010. vCount[ofs]++;
  89011. }
  89012. }
  89013. }
  89014. for (j = 0; j < vCount.length; ++j) {
  89015. if (vCount[j] === 1) {
  89016. this.vertices[vId[j]].isBorder = true;
  89017. }
  89018. else {
  89019. this.vertices[vId[j]].isBorder = false;
  89020. }
  89021. }
  89022. }
  89023. };
  89024. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89025. if (identifyBorders === void 0) { identifyBorders = false; }
  89026. var i;
  89027. if (!identifyBorders) {
  89028. var newTrianglesVector = [];
  89029. for (i = 0; i < this.triangles.length; ++i) {
  89030. if (!this.triangles[i].deleted) {
  89031. newTrianglesVector.push(this.triangles[i]);
  89032. }
  89033. }
  89034. this.triangles = newTrianglesVector;
  89035. }
  89036. for (i = 0; i < this.vertices.length; ++i) {
  89037. this.vertices[i].triangleCount = 0;
  89038. this.vertices[i].triangleStart = 0;
  89039. }
  89040. var t;
  89041. var j;
  89042. var v;
  89043. for (i = 0; i < this.triangles.length; ++i) {
  89044. t = this.triangles[i];
  89045. for (j = 0; j < 3; ++j) {
  89046. v = t.vertices[j];
  89047. v.triangleCount++;
  89048. }
  89049. }
  89050. var tStart = 0;
  89051. for (i = 0; i < this.vertices.length; ++i) {
  89052. this.vertices[i].triangleStart = tStart;
  89053. tStart += this.vertices[i].triangleCount;
  89054. this.vertices[i].triangleCount = 0;
  89055. }
  89056. var newReferences = new Array(this.triangles.length * 3);
  89057. for (i = 0; i < this.triangles.length; ++i) {
  89058. t = this.triangles[i];
  89059. for (j = 0; j < 3; ++j) {
  89060. v = t.vertices[j];
  89061. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89062. v.triangleCount++;
  89063. }
  89064. }
  89065. this.references = newReferences;
  89066. if (identifyBorders) {
  89067. this.identifyBorder();
  89068. }
  89069. };
  89070. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89071. var x = point.x;
  89072. var y = point.y;
  89073. var z = point.z;
  89074. 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
  89075. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89076. };
  89077. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89078. var q = vertex1.q.add(vertex2.q);
  89079. var border = vertex1.isBorder && vertex2.isBorder;
  89080. var error = 0;
  89081. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89082. if (qDet !== 0 && !border) {
  89083. if (!pointResult) {
  89084. pointResult = BABYLON.Vector3.Zero();
  89085. }
  89086. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89087. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89088. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89089. error = this.vertexError(q, pointResult);
  89090. }
  89091. else {
  89092. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89093. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89094. var error1 = this.vertexError(q, vertex1.position);
  89095. var error2 = this.vertexError(q, vertex2.position);
  89096. var error3 = this.vertexError(q, p3);
  89097. error = Math.min(error1, error2, error3);
  89098. if (error === error1) {
  89099. if (pointResult) {
  89100. pointResult.copyFrom(vertex1.position);
  89101. }
  89102. }
  89103. else if (error === error2) {
  89104. if (pointResult) {
  89105. pointResult.copyFrom(vertex2.position);
  89106. }
  89107. }
  89108. else {
  89109. if (pointResult) {
  89110. pointResult.copyFrom(p3);
  89111. }
  89112. }
  89113. }
  89114. return error;
  89115. };
  89116. return QuadraticErrorSimplification;
  89117. }());
  89118. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89119. })(BABYLON || (BABYLON = {}));
  89120. //# sourceMappingURL=babylon.meshSimplification.js.map
  89121. var BABYLON;
  89122. (function (BABYLON) {
  89123. var MeshLODLevel = /** @class */ (function () {
  89124. function MeshLODLevel(distance, mesh) {
  89125. this.distance = distance;
  89126. this.mesh = mesh;
  89127. }
  89128. return MeshLODLevel;
  89129. }());
  89130. BABYLON.MeshLODLevel = MeshLODLevel;
  89131. })(BABYLON || (BABYLON = {}));
  89132. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89133. var BABYLON;
  89134. (function (BABYLON) {
  89135. /**
  89136. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89137. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89138. */
  89139. var SceneOptimization = /** @class */ (function () {
  89140. /**
  89141. * Creates the SceneOptimization object
  89142. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89143. * @param desc defines the description associated with the optimization
  89144. */
  89145. function SceneOptimization(
  89146. /**
  89147. * Defines the priority of this optimization (0 by default which means first in the list)
  89148. */
  89149. priority) {
  89150. if (priority === void 0) { priority = 0; }
  89151. this.priority = priority;
  89152. }
  89153. /**
  89154. * Gets a string describing the action executed by the current optimization
  89155. * @returns description string
  89156. */
  89157. SceneOptimization.prototype.getDescription = function () {
  89158. return "";
  89159. };
  89160. /**
  89161. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89162. * @param scene defines the current scene where to apply this optimization
  89163. * @param optimizer defines the current optimizer
  89164. * @returns true if everything that can be done was applied
  89165. */
  89166. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89167. return true;
  89168. };
  89169. ;
  89170. return SceneOptimization;
  89171. }());
  89172. BABYLON.SceneOptimization = SceneOptimization;
  89173. /**
  89174. * Defines an optimization used to reduce the size of render target textures
  89175. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89176. */
  89177. var TextureOptimization = /** @class */ (function (_super) {
  89178. __extends(TextureOptimization, _super);
  89179. /**
  89180. * Creates the TextureOptimization object
  89181. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89182. * @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
  89183. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89184. */
  89185. function TextureOptimization(
  89186. /**
  89187. * Defines the priority of this optimization (0 by default which means first in the list)
  89188. */
  89189. priority,
  89190. /**
  89191. * 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
  89192. */
  89193. maximumSize,
  89194. /**
  89195. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89196. */
  89197. step) {
  89198. if (priority === void 0) { priority = 0; }
  89199. if (maximumSize === void 0) { maximumSize = 1024; }
  89200. if (step === void 0) { step = 0.5; }
  89201. var _this = _super.call(this, priority) || this;
  89202. _this.priority = priority;
  89203. _this.maximumSize = maximumSize;
  89204. _this.step = step;
  89205. return _this;
  89206. }
  89207. /**
  89208. * Gets a string describing the action executed by the current optimization
  89209. * @returns description string
  89210. */
  89211. TextureOptimization.prototype.getDescription = function () {
  89212. return "Reducing render target texture size to " + this.maximumSize;
  89213. };
  89214. /**
  89215. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89216. * @param scene defines the current scene where to apply this optimization
  89217. * @param optimizer defines the current optimizer
  89218. * @returns true if everything that can be done was applied
  89219. */
  89220. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89221. var allDone = true;
  89222. for (var index = 0; index < scene.textures.length; index++) {
  89223. var texture = scene.textures[index];
  89224. if (!texture.canRescale || texture.getContext) {
  89225. continue;
  89226. }
  89227. var currentSize = texture.getSize();
  89228. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89229. if (maxDimension > this.maximumSize) {
  89230. texture.scale(this.step);
  89231. allDone = false;
  89232. }
  89233. }
  89234. return allDone;
  89235. };
  89236. return TextureOptimization;
  89237. }(SceneOptimization));
  89238. BABYLON.TextureOptimization = TextureOptimization;
  89239. /**
  89240. * Defines an optimization used to increase or decrease the rendering resolution
  89241. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89242. */
  89243. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89244. __extends(HardwareScalingOptimization, _super);
  89245. /**
  89246. * Creates the HardwareScalingOptimization object
  89247. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89248. * @param maximumScale defines the maximum scale to use (2 by default)
  89249. * @param step defines the step to use between two passes (0.5 by default)
  89250. */
  89251. function HardwareScalingOptimization(
  89252. /**
  89253. * Defines the priority of this optimization (0 by default which means first in the list)
  89254. */
  89255. priority,
  89256. /**
  89257. * Defines the maximum scale to use (2 by default)
  89258. */
  89259. maximumScale,
  89260. /**
  89261. * Defines the step to use between two passes (0.5 by default)
  89262. */
  89263. step) {
  89264. if (priority === void 0) { priority = 0; }
  89265. if (maximumScale === void 0) { maximumScale = 2; }
  89266. if (step === void 0) { step = 0.25; }
  89267. var _this = _super.call(this, priority) || this;
  89268. _this.priority = priority;
  89269. _this.maximumScale = maximumScale;
  89270. _this.step = step;
  89271. _this._currentScale = -1;
  89272. _this._directionOffset = 1;
  89273. return _this;
  89274. }
  89275. /**
  89276. * Gets a string describing the action executed by the current optimization
  89277. * @return description string
  89278. */
  89279. HardwareScalingOptimization.prototype.getDescription = function () {
  89280. return "Setting hardware scaling level to " + this._currentScale;
  89281. };
  89282. /**
  89283. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89284. * @param scene defines the current scene where to apply this optimization
  89285. * @param optimizer defines the current optimizer
  89286. * @returns true if everything that can be done was applied
  89287. */
  89288. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89289. if (this._currentScale === -1) {
  89290. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89291. if (this._currentScale > this.maximumScale) {
  89292. this._directionOffset = -1;
  89293. }
  89294. }
  89295. this._currentScale += this._directionOffset * this.step;
  89296. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89297. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89298. };
  89299. ;
  89300. return HardwareScalingOptimization;
  89301. }(SceneOptimization));
  89302. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89303. /**
  89304. * Defines an optimization used to remove shadows
  89305. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89306. */
  89307. var ShadowsOptimization = /** @class */ (function (_super) {
  89308. __extends(ShadowsOptimization, _super);
  89309. function ShadowsOptimization() {
  89310. return _super !== null && _super.apply(this, arguments) || this;
  89311. }
  89312. /**
  89313. * Gets a string describing the action executed by the current optimization
  89314. * @return description string
  89315. */
  89316. ShadowsOptimization.prototype.getDescription = function () {
  89317. return "Turning shadows on/off";
  89318. };
  89319. /**
  89320. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89321. * @param scene defines the current scene where to apply this optimization
  89322. * @param optimizer defines the current optimizer
  89323. * @returns true if everything that can be done was applied
  89324. */
  89325. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89326. scene.shadowsEnabled = optimizer.isInImprovementMode;
  89327. return true;
  89328. };
  89329. ;
  89330. return ShadowsOptimization;
  89331. }(SceneOptimization));
  89332. BABYLON.ShadowsOptimization = ShadowsOptimization;
  89333. /**
  89334. * Defines an optimization used to turn post-processes off
  89335. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89336. */
  89337. var PostProcessesOptimization = /** @class */ (function (_super) {
  89338. __extends(PostProcessesOptimization, _super);
  89339. function PostProcessesOptimization() {
  89340. return _super !== null && _super.apply(this, arguments) || this;
  89341. }
  89342. /**
  89343. * Gets a string describing the action executed by the current optimization
  89344. * @return description string
  89345. */
  89346. PostProcessesOptimization.prototype.getDescription = function () {
  89347. return "Turning post-processes on/off";
  89348. };
  89349. /**
  89350. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89351. * @param scene defines the current scene where to apply this optimization
  89352. * @param optimizer defines the current optimizer
  89353. * @returns true if everything that can be done was applied
  89354. */
  89355. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  89356. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  89357. return true;
  89358. };
  89359. ;
  89360. return PostProcessesOptimization;
  89361. }(SceneOptimization));
  89362. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  89363. /**
  89364. * Defines an optimization used to turn lens flares off
  89365. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89366. */
  89367. var LensFlaresOptimization = /** @class */ (function (_super) {
  89368. __extends(LensFlaresOptimization, _super);
  89369. function LensFlaresOptimization() {
  89370. return _super !== null && _super.apply(this, arguments) || this;
  89371. }
  89372. /**
  89373. * Gets a string describing the action executed by the current optimization
  89374. * @return description string
  89375. */
  89376. LensFlaresOptimization.prototype.getDescription = function () {
  89377. return "Turning lens flares on/off";
  89378. };
  89379. /**
  89380. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89381. * @param scene defines the current scene where to apply this optimization
  89382. * @param optimizer defines the current optimizer
  89383. * @returns true if everything that can be done was applied
  89384. */
  89385. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  89386. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  89387. return true;
  89388. };
  89389. ;
  89390. return LensFlaresOptimization;
  89391. }(SceneOptimization));
  89392. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  89393. /**
  89394. * Defines an optimization based on user defined callback.
  89395. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89396. */
  89397. var CustomOptimization = /** @class */ (function (_super) {
  89398. __extends(CustomOptimization, _super);
  89399. function CustomOptimization() {
  89400. return _super !== null && _super.apply(this, arguments) || this;
  89401. }
  89402. /**
  89403. * Gets a string describing the action executed by the current optimization
  89404. * @returns description string
  89405. */
  89406. CustomOptimization.prototype.getDescription = function () {
  89407. if (this.onGetDescription) {
  89408. return this.onGetDescription();
  89409. }
  89410. return "Running user defined callback";
  89411. };
  89412. /**
  89413. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89414. * @param scene defines the current scene where to apply this optimization
  89415. * @param optimizer defines the current optimizer
  89416. * @returns true if everything that can be done was applied
  89417. */
  89418. CustomOptimization.prototype.apply = function (scene, optimizer) {
  89419. if (this.onApply) {
  89420. return this.onApply(scene, optimizer);
  89421. }
  89422. return true;
  89423. };
  89424. ;
  89425. return CustomOptimization;
  89426. }(SceneOptimization));
  89427. BABYLON.CustomOptimization = CustomOptimization;
  89428. /**
  89429. * Defines an optimization used to turn particles off
  89430. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89431. */
  89432. var ParticlesOptimization = /** @class */ (function (_super) {
  89433. __extends(ParticlesOptimization, _super);
  89434. function ParticlesOptimization() {
  89435. return _super !== null && _super.apply(this, arguments) || this;
  89436. }
  89437. /**
  89438. * Gets a string describing the action executed by the current optimization
  89439. * @return description string
  89440. */
  89441. ParticlesOptimization.prototype.getDescription = function () {
  89442. return "Turning particles on/off";
  89443. };
  89444. /**
  89445. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89446. * @param scene defines the current scene where to apply this optimization
  89447. * @param optimizer defines the current optimizer
  89448. * @returns true if everything that can be done was applied
  89449. */
  89450. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  89451. scene.particlesEnabled = optimizer.isInImprovementMode;
  89452. return true;
  89453. };
  89454. ;
  89455. return ParticlesOptimization;
  89456. }(SceneOptimization));
  89457. BABYLON.ParticlesOptimization = ParticlesOptimization;
  89458. /**
  89459. * Defines an optimization used to turn render targets off
  89460. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89461. */
  89462. var RenderTargetsOptimization = /** @class */ (function (_super) {
  89463. __extends(RenderTargetsOptimization, _super);
  89464. function RenderTargetsOptimization() {
  89465. return _super !== null && _super.apply(this, arguments) || this;
  89466. }
  89467. /**
  89468. * Gets a string describing the action executed by the current optimization
  89469. * @return description string
  89470. */
  89471. RenderTargetsOptimization.prototype.getDescription = function () {
  89472. return "Turning render targets off";
  89473. };
  89474. /**
  89475. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89476. * @param scene defines the current scene where to apply this optimization
  89477. * @param optimizer defines the current optimizer
  89478. * @returns true if everything that can be done was applied
  89479. */
  89480. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  89481. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  89482. return true;
  89483. };
  89484. ;
  89485. return RenderTargetsOptimization;
  89486. }(SceneOptimization));
  89487. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  89488. /**
  89489. * Defines an optimization used to merge meshes with compatible materials
  89490. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89491. */
  89492. var MergeMeshesOptimization = /** @class */ (function (_super) {
  89493. __extends(MergeMeshesOptimization, _super);
  89494. function MergeMeshesOptimization() {
  89495. var _this = _super !== null && _super.apply(this, arguments) || this;
  89496. _this._canBeMerged = function (abstractMesh) {
  89497. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  89498. return false;
  89499. }
  89500. var mesh = abstractMesh;
  89501. if (!mesh.isVisible || !mesh.isEnabled()) {
  89502. return false;
  89503. }
  89504. if (mesh.instances.length > 0) {
  89505. return false;
  89506. }
  89507. if (mesh.skeleton || mesh.hasLODLevels) {
  89508. return false;
  89509. }
  89510. if (mesh.parent) {
  89511. return false;
  89512. }
  89513. return true;
  89514. };
  89515. return _this;
  89516. }
  89517. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  89518. /**
  89519. * Gets or sets a boolean which defines if optimization octree has to be updated
  89520. */
  89521. get: function () {
  89522. return MergeMeshesOptimization._UpdateSelectionTree;
  89523. },
  89524. /**
  89525. * Gets or sets a boolean which defines if optimization octree has to be updated
  89526. */
  89527. set: function (value) {
  89528. MergeMeshesOptimization._UpdateSelectionTree = value;
  89529. },
  89530. enumerable: true,
  89531. configurable: true
  89532. });
  89533. /**
  89534. * Gets a string describing the action executed by the current optimization
  89535. * @return description string
  89536. */
  89537. MergeMeshesOptimization.prototype.getDescription = function () {
  89538. return "Merging similar meshes together";
  89539. };
  89540. /**
  89541. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89542. * @param scene defines the current scene where to apply this optimization
  89543. * @param optimizer defines the current optimizer
  89544. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  89545. * @returns true if everything that can be done was applied
  89546. */
  89547. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  89548. var globalPool = scene.meshes.slice(0);
  89549. var globalLength = globalPool.length;
  89550. for (var index = 0; index < globalLength; index++) {
  89551. var currentPool = new Array();
  89552. var current = globalPool[index];
  89553. // Checks
  89554. if (!this._canBeMerged(current)) {
  89555. continue;
  89556. }
  89557. currentPool.push(current);
  89558. // Find compatible meshes
  89559. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89560. var otherMesh = globalPool[subIndex];
  89561. if (!this._canBeMerged(otherMesh)) {
  89562. continue;
  89563. }
  89564. if (otherMesh.material !== current.material) {
  89565. continue;
  89566. }
  89567. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89568. continue;
  89569. }
  89570. currentPool.push(otherMesh);
  89571. globalLength--;
  89572. globalPool.splice(subIndex, 1);
  89573. subIndex--;
  89574. }
  89575. if (currentPool.length < 2) {
  89576. continue;
  89577. }
  89578. // Merge meshes
  89579. BABYLON.Mesh.MergeMeshes(currentPool);
  89580. }
  89581. if (updateSelectionTree != undefined) {
  89582. if (updateSelectionTree) {
  89583. scene.createOrUpdateSelectionOctree();
  89584. }
  89585. }
  89586. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89587. scene.createOrUpdateSelectionOctree();
  89588. }
  89589. return true;
  89590. };
  89591. ;
  89592. MergeMeshesOptimization._UpdateSelectionTree = false;
  89593. return MergeMeshesOptimization;
  89594. }(SceneOptimization));
  89595. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89596. /**
  89597. * Defines a list of options used by SceneOptimizer
  89598. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89599. */
  89600. var SceneOptimizerOptions = /** @class */ (function () {
  89601. /**
  89602. * Creates a new list of options used by SceneOptimizer
  89603. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89604. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89605. */
  89606. function SceneOptimizerOptions(
  89607. /**
  89608. * Defines the target frame rate to reach (60 by default)
  89609. */
  89610. targetFrameRate,
  89611. /**
  89612. * Defines the interval between two checkes (2000ms by default)
  89613. */
  89614. trackerDuration) {
  89615. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89616. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89617. this.targetFrameRate = targetFrameRate;
  89618. this.trackerDuration = trackerDuration;
  89619. /**
  89620. * Gets the list of optimizations to apply
  89621. */
  89622. this.optimizations = new Array();
  89623. }
  89624. /**
  89625. * Add a new optimization
  89626. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89627. * @returns the current SceneOptimizerOptions
  89628. */
  89629. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89630. this.optimizations.push(optimization);
  89631. return this;
  89632. };
  89633. /**
  89634. * Add a new custom optimization
  89635. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89636. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89637. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89638. * @returns the current SceneOptimizerOptions
  89639. */
  89640. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89641. if (priority === void 0) { priority = 0; }
  89642. var optimization = new CustomOptimization(priority);
  89643. optimization.onApply = onApply;
  89644. optimization.onGetDescription = onGetDescription;
  89645. this.optimizations.push(optimization);
  89646. return this;
  89647. };
  89648. /**
  89649. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89650. * @param targetFrameRate defines the target frame rate (60 by default)
  89651. * @returns a SceneOptimizerOptions object
  89652. */
  89653. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89654. var result = new SceneOptimizerOptions(targetFrameRate);
  89655. var priority = 0;
  89656. result.addOptimization(new MergeMeshesOptimization(priority));
  89657. result.addOptimization(new ShadowsOptimization(priority));
  89658. result.addOptimization(new LensFlaresOptimization(priority));
  89659. // Next priority
  89660. priority++;
  89661. result.addOptimization(new PostProcessesOptimization(priority));
  89662. result.addOptimization(new ParticlesOptimization(priority));
  89663. // Next priority
  89664. priority++;
  89665. result.addOptimization(new TextureOptimization(priority, 1024));
  89666. return result;
  89667. };
  89668. /**
  89669. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89670. * @param targetFrameRate defines the target frame rate (60 by default)
  89671. * @returns a SceneOptimizerOptions object
  89672. */
  89673. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89674. var result = new SceneOptimizerOptions(targetFrameRate);
  89675. var priority = 0;
  89676. result.addOptimization(new MergeMeshesOptimization(priority));
  89677. result.addOptimization(new ShadowsOptimization(priority));
  89678. result.addOptimization(new LensFlaresOptimization(priority));
  89679. // Next priority
  89680. priority++;
  89681. result.addOptimization(new PostProcessesOptimization(priority));
  89682. result.addOptimization(new ParticlesOptimization(priority));
  89683. // Next priority
  89684. priority++;
  89685. result.addOptimization(new TextureOptimization(priority, 512));
  89686. // Next priority
  89687. priority++;
  89688. result.addOptimization(new RenderTargetsOptimization(priority));
  89689. // Next priority
  89690. priority++;
  89691. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89692. return result;
  89693. };
  89694. /**
  89695. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89696. * @param targetFrameRate defines the target frame rate (60 by default)
  89697. * @returns a SceneOptimizerOptions object
  89698. */
  89699. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89700. var result = new SceneOptimizerOptions(targetFrameRate);
  89701. var priority = 0;
  89702. result.addOptimization(new MergeMeshesOptimization(priority));
  89703. result.addOptimization(new ShadowsOptimization(priority));
  89704. result.addOptimization(new LensFlaresOptimization(priority));
  89705. // Next priority
  89706. priority++;
  89707. result.addOptimization(new PostProcessesOptimization(priority));
  89708. result.addOptimization(new ParticlesOptimization(priority));
  89709. // Next priority
  89710. priority++;
  89711. result.addOptimization(new TextureOptimization(priority, 256));
  89712. // Next priority
  89713. priority++;
  89714. result.addOptimization(new RenderTargetsOptimization(priority));
  89715. // Next priority
  89716. priority++;
  89717. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89718. return result;
  89719. };
  89720. return SceneOptimizerOptions;
  89721. }());
  89722. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89723. /**
  89724. * Class used to run optimizations in order to reach a target frame rate
  89725. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89726. */
  89727. var SceneOptimizer = /** @class */ (function () {
  89728. /**
  89729. * Creates a new SceneOptimizer
  89730. * @param scene defines the scene to work on
  89731. * @param options defines the options to use with the SceneOptimizer
  89732. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89733. * @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)
  89734. */
  89735. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89736. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89737. if (improvementMode === void 0) { improvementMode = false; }
  89738. var _this = this;
  89739. this._isRunning = false;
  89740. this._currentPriorityLevel = 0;
  89741. this._targetFrameRate = 60;
  89742. this._trackerDuration = 2000;
  89743. this._currentFrameRate = 0;
  89744. this._improvementMode = false;
  89745. /**
  89746. * Defines an observable called when the optimizer reaches the target frame rate
  89747. */
  89748. this.onSuccessObservable = new BABYLON.Observable();
  89749. /**
  89750. * Defines an observable called when the optimizer enables an optimization
  89751. */
  89752. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89753. /**
  89754. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89755. */
  89756. this.onFailureObservable = new BABYLON.Observable();
  89757. if (!options) {
  89758. this._options = new SceneOptimizerOptions();
  89759. }
  89760. else {
  89761. this._options = options;
  89762. }
  89763. if (this._options.targetFrameRate) {
  89764. this._targetFrameRate = this._options.targetFrameRate;
  89765. }
  89766. if (this._options.trackerDuration) {
  89767. this._trackerDuration = this._options.trackerDuration;
  89768. }
  89769. if (autoGeneratePriorities) {
  89770. var priority = 0;
  89771. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89772. var optim = _a[_i];
  89773. optim.priority = priority++;
  89774. }
  89775. }
  89776. this._improvementMode = improvementMode;
  89777. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89778. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89779. _this._sceneDisposeObserver = null;
  89780. _this.dispose();
  89781. });
  89782. }
  89783. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89784. /**
  89785. * Gets a boolean indicating if the optimizer is in improvement mode
  89786. */
  89787. get: function () {
  89788. return this._improvementMode;
  89789. },
  89790. enumerable: true,
  89791. configurable: true
  89792. });
  89793. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89794. /**
  89795. * Gets the current priority level (0 at start)
  89796. */
  89797. get: function () {
  89798. return this._currentPriorityLevel;
  89799. },
  89800. enumerable: true,
  89801. configurable: true
  89802. });
  89803. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89804. /**
  89805. * Gets the current frame rate checked by the SceneOptimizer
  89806. */
  89807. get: function () {
  89808. return this._currentFrameRate;
  89809. },
  89810. enumerable: true,
  89811. configurable: true
  89812. });
  89813. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  89814. /**
  89815. * Gets or sets the current target frame rate (60 by default)
  89816. */
  89817. get: function () {
  89818. return this._targetFrameRate;
  89819. },
  89820. /**
  89821. * Gets or sets the current target frame rate (60 by default)
  89822. */
  89823. set: function (value) {
  89824. this._targetFrameRate = value;
  89825. },
  89826. enumerable: true,
  89827. configurable: true
  89828. });
  89829. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  89830. /**
  89831. * Gets or sets the current interval between two checks (every 2000ms by default)
  89832. */
  89833. get: function () {
  89834. return this._trackerDuration;
  89835. },
  89836. /**
  89837. * Gets or sets the current interval between two checks (every 2000ms by default)
  89838. */
  89839. set: function (value) {
  89840. this._trackerDuration = value;
  89841. },
  89842. enumerable: true,
  89843. configurable: true
  89844. });
  89845. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  89846. /**
  89847. * Gets the list of active optimizations
  89848. */
  89849. get: function () {
  89850. return this._options.optimizations;
  89851. },
  89852. enumerable: true,
  89853. configurable: true
  89854. });
  89855. /**
  89856. * Stops the current optimizer
  89857. */
  89858. SceneOptimizer.prototype.stop = function () {
  89859. this._isRunning = false;
  89860. };
  89861. /**
  89862. * Reset the optimizer to initial step (current priority level = 0)
  89863. */
  89864. SceneOptimizer.prototype.reset = function () {
  89865. this._currentPriorityLevel = 0;
  89866. };
  89867. /**
  89868. * Start the optimizer. By default it will try to reach a specific framerate
  89869. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  89870. */
  89871. SceneOptimizer.prototype.start = function () {
  89872. var _this = this;
  89873. if (this._isRunning) {
  89874. return;
  89875. }
  89876. this._isRunning = true;
  89877. // Let's wait for the scene to be ready before running our check
  89878. this._scene.executeWhenReady(function () {
  89879. setTimeout(function () {
  89880. _this._checkCurrentState();
  89881. }, _this._trackerDuration);
  89882. });
  89883. };
  89884. SceneOptimizer.prototype._checkCurrentState = function () {
  89885. var _this = this;
  89886. if (!this._isRunning) {
  89887. return;
  89888. }
  89889. var scene = this._scene;
  89890. var options = this._options;
  89891. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  89892. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  89893. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  89894. this._isRunning = false;
  89895. this.onSuccessObservable.notifyObservers(this);
  89896. return;
  89897. }
  89898. // Apply current level of optimizations
  89899. var allDone = true;
  89900. var noOptimizationApplied = true;
  89901. for (var index = 0; index < options.optimizations.length; index++) {
  89902. var optimization = options.optimizations[index];
  89903. if (optimization.priority === this._currentPriorityLevel) {
  89904. noOptimizationApplied = false;
  89905. allDone = allDone && optimization.apply(scene, this);
  89906. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  89907. }
  89908. }
  89909. // If no optimization was applied, this is a failure :(
  89910. if (noOptimizationApplied) {
  89911. this._isRunning = false;
  89912. this.onFailureObservable.notifyObservers(this);
  89913. return;
  89914. }
  89915. // If all optimizations were done, move to next level
  89916. if (allDone) {
  89917. this._currentPriorityLevel++;
  89918. }
  89919. // Let's the system running for a specific amount of time before checking FPS
  89920. scene.executeWhenReady(function () {
  89921. setTimeout(function () {
  89922. _this._checkCurrentState();
  89923. }, _this._trackerDuration);
  89924. });
  89925. };
  89926. /**
  89927. * Release all resources
  89928. */
  89929. SceneOptimizer.prototype.dispose = function () {
  89930. this.stop();
  89931. this.onSuccessObservable.clear();
  89932. this.onFailureObservable.clear();
  89933. this.onNewOptimizationAppliedObservable.clear();
  89934. if (this._sceneDisposeObserver) {
  89935. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  89936. }
  89937. };
  89938. /**
  89939. * Helper function to create a SceneOptimizer with one single line of code
  89940. * @param scene defines the scene to work on
  89941. * @param options defines the options to use with the SceneOptimizer
  89942. * @param onSuccess defines a callback to call on success
  89943. * @param onFailure defines a callback to call on failure
  89944. * @returns the new SceneOptimizer object
  89945. */
  89946. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  89947. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  89948. if (onSuccess) {
  89949. optimizer.onSuccessObservable.add(function () {
  89950. onSuccess();
  89951. });
  89952. }
  89953. if (onFailure) {
  89954. optimizer.onFailureObservable.add(function () {
  89955. onFailure();
  89956. });
  89957. }
  89958. optimizer.start();
  89959. return optimizer;
  89960. };
  89961. return SceneOptimizer;
  89962. }());
  89963. BABYLON.SceneOptimizer = SceneOptimizer;
  89964. })(BABYLON || (BABYLON = {}));
  89965. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  89966. var BABYLON;
  89967. (function (BABYLON) {
  89968. var OutlineRenderer = /** @class */ (function () {
  89969. function OutlineRenderer(scene) {
  89970. this.zOffset = 1;
  89971. this._scene = scene;
  89972. }
  89973. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  89974. var _this = this;
  89975. if (useOverlay === void 0) { useOverlay = false; }
  89976. var scene = this._scene;
  89977. var engine = this._scene.getEngine();
  89978. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  89979. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  89980. return;
  89981. }
  89982. var mesh = subMesh.getRenderingMesh();
  89983. var material = subMesh.getMaterial();
  89984. if (!material || !scene.activeCamera) {
  89985. return;
  89986. }
  89987. engine.enableEffect(this._effect);
  89988. // Logarithmic depth
  89989. if (material.useLogarithmicDepth) {
  89990. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  89991. }
  89992. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  89993. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  89994. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  89995. // Bones
  89996. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89997. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89998. }
  89999. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90000. // Alpha test
  90001. if (material && material.needAlphaTesting()) {
  90002. var alphaTexture = material.getAlphaTestTexture();
  90003. if (alphaTexture) {
  90004. this._effect.setTexture("diffuseSampler", alphaTexture);
  90005. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90006. }
  90007. }
  90008. engine.setZOffset(-this.zOffset);
  90009. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90010. engine.setZOffset(0);
  90011. };
  90012. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90013. var defines = [];
  90014. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90015. var mesh = subMesh.getMesh();
  90016. var material = subMesh.getMaterial();
  90017. if (material) {
  90018. // Alpha test
  90019. if (material.needAlphaTesting()) {
  90020. defines.push("#define ALPHATEST");
  90021. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90022. attribs.push(BABYLON.VertexBuffer.UVKind);
  90023. defines.push("#define UV1");
  90024. }
  90025. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90026. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90027. defines.push("#define UV2");
  90028. }
  90029. }
  90030. //Logarithmic depth
  90031. if (material.useLogarithmicDepth) {
  90032. defines.push("#define LOGARITHMICDEPTH");
  90033. }
  90034. }
  90035. // Bones
  90036. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90037. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90038. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90039. if (mesh.numBoneInfluencers > 4) {
  90040. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90041. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90042. }
  90043. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90044. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90045. }
  90046. else {
  90047. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90048. }
  90049. // Instances
  90050. if (useInstances) {
  90051. defines.push("#define INSTANCES");
  90052. attribs.push("world0");
  90053. attribs.push("world1");
  90054. attribs.push("world2");
  90055. attribs.push("world3");
  90056. }
  90057. // Get correct effect
  90058. var join = defines.join("\n");
  90059. if (this._cachedDefines !== join) {
  90060. this._cachedDefines = join;
  90061. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90062. }
  90063. return this._effect.isReady();
  90064. };
  90065. return OutlineRenderer;
  90066. }());
  90067. BABYLON.OutlineRenderer = OutlineRenderer;
  90068. })(BABYLON || (BABYLON = {}));
  90069. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90070. var BABYLON;
  90071. (function (BABYLON) {
  90072. var FaceAdjacencies = /** @class */ (function () {
  90073. function FaceAdjacencies() {
  90074. this.edges = new Array();
  90075. this.edgesConnectedCount = 0;
  90076. }
  90077. return FaceAdjacencies;
  90078. }());
  90079. var EdgesRenderer = /** @class */ (function () {
  90080. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90081. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90082. if (epsilon === void 0) { epsilon = 0.95; }
  90083. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90084. this.edgesWidthScalerForOrthographic = 1000.0;
  90085. this.edgesWidthScalerForPerspective = 50.0;
  90086. this._linesPositions = new Array();
  90087. this._linesNormals = new Array();
  90088. this._linesIndices = new Array();
  90089. this._buffers = {};
  90090. this._checkVerticesInsteadOfIndices = false;
  90091. this._source = source;
  90092. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90093. this._epsilon = epsilon;
  90094. this._prepareRessources();
  90095. this._generateEdgesLines();
  90096. }
  90097. EdgesRenderer.prototype._prepareRessources = function () {
  90098. if (this._lineShader) {
  90099. return;
  90100. }
  90101. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90102. attributes: ["position", "normal"],
  90103. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90104. });
  90105. this._lineShader.disableDepthWrite = true;
  90106. this._lineShader.backFaceCulling = false;
  90107. };
  90108. EdgesRenderer.prototype._rebuild = function () {
  90109. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90110. if (buffer) {
  90111. buffer._rebuild();
  90112. }
  90113. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90114. if (buffer) {
  90115. buffer._rebuild();
  90116. }
  90117. var scene = this._source.getScene();
  90118. var engine = scene.getEngine();
  90119. this._ib = engine.createIndexBuffer(this._linesIndices);
  90120. };
  90121. EdgesRenderer.prototype.dispose = function () {
  90122. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90123. if (buffer) {
  90124. buffer.dispose();
  90125. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90126. }
  90127. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90128. if (buffer) {
  90129. buffer.dispose();
  90130. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90131. }
  90132. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90133. this._lineShader.dispose();
  90134. };
  90135. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90136. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90137. return 0;
  90138. }
  90139. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90140. return 1;
  90141. }
  90142. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90143. return 2;
  90144. }
  90145. return -1;
  90146. };
  90147. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90148. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90149. return 0;
  90150. }
  90151. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90152. return 1;
  90153. }
  90154. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90155. return 2;
  90156. }
  90157. return -1;
  90158. };
  90159. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90160. var needToCreateLine;
  90161. if (edge === undefined) {
  90162. needToCreateLine = true;
  90163. }
  90164. else {
  90165. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90166. needToCreateLine = dotProduct < this._epsilon;
  90167. }
  90168. if (needToCreateLine) {
  90169. var offset = this._linesPositions.length / 3;
  90170. var normal = p0.subtract(p1);
  90171. normal.normalize();
  90172. // Positions
  90173. this._linesPositions.push(p0.x);
  90174. this._linesPositions.push(p0.y);
  90175. this._linesPositions.push(p0.z);
  90176. this._linesPositions.push(p0.x);
  90177. this._linesPositions.push(p0.y);
  90178. this._linesPositions.push(p0.z);
  90179. this._linesPositions.push(p1.x);
  90180. this._linesPositions.push(p1.y);
  90181. this._linesPositions.push(p1.z);
  90182. this._linesPositions.push(p1.x);
  90183. this._linesPositions.push(p1.y);
  90184. this._linesPositions.push(p1.z);
  90185. // Normals
  90186. this._linesNormals.push(p1.x);
  90187. this._linesNormals.push(p1.y);
  90188. this._linesNormals.push(p1.z);
  90189. this._linesNormals.push(-1);
  90190. this._linesNormals.push(p1.x);
  90191. this._linesNormals.push(p1.y);
  90192. this._linesNormals.push(p1.z);
  90193. this._linesNormals.push(1);
  90194. this._linesNormals.push(p0.x);
  90195. this._linesNormals.push(p0.y);
  90196. this._linesNormals.push(p0.z);
  90197. this._linesNormals.push(-1);
  90198. this._linesNormals.push(p0.x);
  90199. this._linesNormals.push(p0.y);
  90200. this._linesNormals.push(p0.z);
  90201. this._linesNormals.push(1);
  90202. // Indices
  90203. this._linesIndices.push(offset);
  90204. this._linesIndices.push(offset + 1);
  90205. this._linesIndices.push(offset + 2);
  90206. this._linesIndices.push(offset);
  90207. this._linesIndices.push(offset + 2);
  90208. this._linesIndices.push(offset + 3);
  90209. }
  90210. };
  90211. EdgesRenderer.prototype._generateEdgesLines = function () {
  90212. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90213. var indices = this._source.getIndices();
  90214. if (!indices || !positions) {
  90215. return;
  90216. }
  90217. // First let's find adjacencies
  90218. var adjacencies = new Array();
  90219. var faceNormals = new Array();
  90220. var index;
  90221. var faceAdjacencies;
  90222. // Prepare faces
  90223. for (index = 0; index < indices.length; index += 3) {
  90224. faceAdjacencies = new FaceAdjacencies();
  90225. var p0Index = indices[index];
  90226. var p1Index = indices[index + 1];
  90227. var p2Index = indices[index + 2];
  90228. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90229. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90230. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90231. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90232. faceNormal.normalize();
  90233. faceNormals.push(faceNormal);
  90234. adjacencies.push(faceAdjacencies);
  90235. }
  90236. // Scan
  90237. for (index = 0; index < adjacencies.length; index++) {
  90238. faceAdjacencies = adjacencies[index];
  90239. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90240. var otherFaceAdjacencies = adjacencies[otherIndex];
  90241. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90242. break;
  90243. }
  90244. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90245. continue;
  90246. }
  90247. var otherP0 = indices[otherIndex * 3];
  90248. var otherP1 = indices[otherIndex * 3 + 1];
  90249. var otherP2 = indices[otherIndex * 3 + 2];
  90250. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90251. var otherEdgeIndex = 0;
  90252. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90253. continue;
  90254. }
  90255. switch (edgeIndex) {
  90256. case 0:
  90257. if (this._checkVerticesInsteadOfIndices) {
  90258. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90259. }
  90260. else {
  90261. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90262. }
  90263. break;
  90264. case 1:
  90265. if (this._checkVerticesInsteadOfIndices) {
  90266. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90267. }
  90268. else {
  90269. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90270. }
  90271. break;
  90272. case 2:
  90273. if (this._checkVerticesInsteadOfIndices) {
  90274. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90275. }
  90276. else {
  90277. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90278. }
  90279. break;
  90280. }
  90281. if (otherEdgeIndex === -1) {
  90282. continue;
  90283. }
  90284. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90285. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90286. faceAdjacencies.edgesConnectedCount++;
  90287. otherFaceAdjacencies.edgesConnectedCount++;
  90288. if (faceAdjacencies.edgesConnectedCount === 3) {
  90289. break;
  90290. }
  90291. }
  90292. }
  90293. }
  90294. // Create lines
  90295. for (index = 0; index < adjacencies.length; index++) {
  90296. // 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
  90297. var current = adjacencies[index];
  90298. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90299. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90300. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90301. }
  90302. // Merge into a single mesh
  90303. var engine = this._source.getScene().getEngine();
  90304. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90305. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90306. this._ib = engine.createIndexBuffer(this._linesIndices);
  90307. this._indicesCount = this._linesIndices.length;
  90308. };
  90309. EdgesRenderer.prototype.render = function () {
  90310. var scene = this._source.getScene();
  90311. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90312. return;
  90313. }
  90314. var engine = scene.getEngine();
  90315. this._lineShader._preBind();
  90316. // VBOs
  90317. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90318. scene.resetCachedMaterial();
  90319. this._lineShader.setColor4("color", this._source.edgesColor);
  90320. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90321. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90322. }
  90323. else {
  90324. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90325. }
  90326. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  90327. this._lineShader.bind(this._source.getWorldMatrix());
  90328. // Draw order
  90329. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  90330. this._lineShader.unbind();
  90331. engine.setDepthWrite(true);
  90332. };
  90333. return EdgesRenderer;
  90334. }());
  90335. BABYLON.EdgesRenderer = EdgesRenderer;
  90336. })(BABYLON || (BABYLON = {}));
  90337. //# sourceMappingURL=babylon.edgesRenderer.js.map
  90338. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90339. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90340. s = arguments[i];
  90341. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90342. t[p] = s[p];
  90343. }
  90344. return t;
  90345. };
  90346. var BABYLON;
  90347. (function (BABYLON) {
  90348. /**
  90349. * The effect layer Helps adding post process effect blended with the main pass.
  90350. *
  90351. * This can be for instance use to generate glow or higlight effects on the scene.
  90352. *
  90353. * The effect layer class can not be used directly and is intented to inherited from to be
  90354. * customized per effects.
  90355. */
  90356. var EffectLayer = /** @class */ (function () {
  90357. /**
  90358. * Instantiates a new effect Layer and references it in the scene.
  90359. * @param name The name of the layer
  90360. * @param scene The scene to use the layer in
  90361. */
  90362. function EffectLayer(
  90363. /** The Friendly of the effect in the scene */
  90364. name, scene) {
  90365. this._vertexBuffers = {};
  90366. this._maxSize = 0;
  90367. this._mainTextureDesiredSize = { width: 0, height: 0 };
  90368. this._shouldRender = true;
  90369. this._postProcesses = [];
  90370. this._textures = [];
  90371. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  90372. /**
  90373. * The clear color of the texture used to generate the glow map.
  90374. */
  90375. this.neutralColor = new BABYLON.Color4();
  90376. /**
  90377. * Specifies wether the highlight layer is enabled or not.
  90378. */
  90379. this.isEnabled = true;
  90380. /**
  90381. * An event triggered when the effect layer has been disposed.
  90382. */
  90383. this.onDisposeObservable = new BABYLON.Observable();
  90384. /**
  90385. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  90386. */
  90387. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  90388. /**
  90389. * An event triggered when the generated texture is being merged in the scene.
  90390. */
  90391. this.onBeforeComposeObservable = new BABYLON.Observable();
  90392. /**
  90393. * An event triggered when the generated texture has been merged in the scene.
  90394. */
  90395. this.onAfterComposeObservable = new BABYLON.Observable();
  90396. /**
  90397. * An event triggered when the efffect layer changes its size.
  90398. */
  90399. this.onSizeChangedObservable = new BABYLON.Observable();
  90400. this.name = name;
  90401. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90402. this._engine = scene.getEngine();
  90403. this._maxSize = this._engine.getCaps().maxTextureSize;
  90404. this._scene.effectLayers.push(this);
  90405. // Generate Buffers
  90406. this._generateIndexBuffer();
  90407. this._genrateVertexBuffer();
  90408. }
  90409. Object.defineProperty(EffectLayer.prototype, "camera", {
  90410. /**
  90411. * Gets the camera attached to the layer.
  90412. */
  90413. get: function () {
  90414. return this._effectLayerOptions.camera;
  90415. },
  90416. enumerable: true,
  90417. configurable: true
  90418. });
  90419. /**
  90420. * Initializes the effect layer with the required options.
  90421. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  90422. */
  90423. EffectLayer.prototype._init = function (options) {
  90424. // Adapt options
  90425. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90426. this._setMainTextureSize();
  90427. this._createMainTexture();
  90428. this._createTextureAndPostProcesses();
  90429. this._mergeEffect = this._createMergeEffect();
  90430. };
  90431. /**
  90432. * Generates the index buffer of the full screen quad blending to the main canvas.
  90433. */
  90434. EffectLayer.prototype._generateIndexBuffer = function () {
  90435. // Indices
  90436. var indices = [];
  90437. indices.push(0);
  90438. indices.push(1);
  90439. indices.push(2);
  90440. indices.push(0);
  90441. indices.push(2);
  90442. indices.push(3);
  90443. this._indexBuffer = this._engine.createIndexBuffer(indices);
  90444. };
  90445. /**
  90446. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  90447. */
  90448. EffectLayer.prototype._genrateVertexBuffer = function () {
  90449. // VBO
  90450. var vertices = [];
  90451. vertices.push(1, 1);
  90452. vertices.push(-1, 1);
  90453. vertices.push(-1, -1);
  90454. vertices.push(1, -1);
  90455. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  90457. };
  90458. /**
  90459. * Sets the main texture desired size which is the closest power of two
  90460. * of the engine canvas size.
  90461. */
  90462. EffectLayer.prototype._setMainTextureSize = function () {
  90463. if (this._effectLayerOptions.mainTextureFixedSize) {
  90464. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  90465. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  90466. }
  90467. else {
  90468. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  90469. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  90470. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  90471. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  90472. }
  90473. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  90474. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  90475. };
  90476. /**
  90477. * Creates the main texture for the effect layer.
  90478. */
  90479. EffectLayer.prototype._createMainTexture = function () {
  90480. var _this = this;
  90481. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  90482. width: this._mainTextureDesiredSize.width,
  90483. height: this._mainTextureDesiredSize.height
  90484. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90485. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  90486. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90487. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90488. this._mainTexture.anisotropicFilteringLevel = 1;
  90489. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90490. this._mainTexture.renderParticles = false;
  90491. this._mainTexture.renderList = null;
  90492. this._mainTexture.ignoreCameraViewport = true;
  90493. // Custom render function
  90494. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90495. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  90496. var index;
  90497. var engine = _this._scene.getEngine();
  90498. if (depthOnlySubMeshes.length) {
  90499. engine.setColorWrite(false);
  90500. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90501. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  90502. }
  90503. engine.setColorWrite(true);
  90504. }
  90505. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90506. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  90507. }
  90508. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90509. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  90510. }
  90511. for (index = 0; index < transparentSubMeshes.length; index++) {
  90512. _this._renderSubMesh(transparentSubMeshes.data[index]);
  90513. }
  90514. };
  90515. this._mainTexture.onClearObservable.add(function (engine) {
  90516. engine.clear(_this.neutralColor, true, true, true);
  90517. });
  90518. };
  90519. /**
  90520. * Checks for the readiness of the element composing the layer.
  90521. * @param subMesh the mesh to check for
  90522. * @param useInstances specify wether or not to use instances to render the mesh
  90523. * @param emissiveTexture the associated emissive texture used to generate the glow
  90524. * @return true if ready otherwise, false
  90525. */
  90526. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  90527. var material = subMesh.getMaterial();
  90528. if (!material) {
  90529. return false;
  90530. }
  90531. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  90532. return false;
  90533. }
  90534. var defines = [];
  90535. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90536. var mesh = subMesh.getMesh();
  90537. var uv1 = false;
  90538. var uv2 = false;
  90539. // Alpha test
  90540. if (material && material.needAlphaTesting()) {
  90541. var alphaTexture = material.getAlphaTestTexture();
  90542. if (alphaTexture) {
  90543. defines.push("#define ALPHATEST");
  90544. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90545. alphaTexture.coordinatesIndex === 1) {
  90546. defines.push("#define DIFFUSEUV2");
  90547. uv2 = true;
  90548. }
  90549. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90550. defines.push("#define DIFFUSEUV1");
  90551. uv1 = true;
  90552. }
  90553. }
  90554. }
  90555. // Emissive
  90556. if (emissiveTexture) {
  90557. defines.push("#define EMISSIVE");
  90558. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90559. emissiveTexture.coordinatesIndex === 1) {
  90560. defines.push("#define EMISSIVEUV2");
  90561. uv2 = true;
  90562. }
  90563. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90564. defines.push("#define EMISSIVEUV1");
  90565. uv1 = true;
  90566. }
  90567. }
  90568. if (uv1) {
  90569. attribs.push(BABYLON.VertexBuffer.UVKind);
  90570. defines.push("#define UV1");
  90571. }
  90572. if (uv2) {
  90573. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90574. defines.push("#define UV2");
  90575. }
  90576. // Bones
  90577. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90580. if (mesh.numBoneInfluencers > 4) {
  90581. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90582. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90583. }
  90584. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90585. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90586. }
  90587. else {
  90588. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90589. }
  90590. // Morph targets
  90591. var manager = mesh.morphTargetManager;
  90592. var morphInfluencers = 0;
  90593. if (manager) {
  90594. if (manager.numInfluencers > 0) {
  90595. defines.push("#define MORPHTARGETS");
  90596. morphInfluencers = manager.numInfluencers;
  90597. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90598. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90599. }
  90600. }
  90601. // Instances
  90602. if (useInstances) {
  90603. defines.push("#define INSTANCES");
  90604. attribs.push("world0");
  90605. attribs.push("world1");
  90606. attribs.push("world2");
  90607. attribs.push("world3");
  90608. }
  90609. // Get correct effect
  90610. var join = defines.join("\n");
  90611. if (this._cachedDefines !== join) {
  90612. this._cachedDefines = join;
  90613. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90614. }
  90615. return this._effectLayerMapGenerationEffect.isReady();
  90616. };
  90617. /**
  90618. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90619. */
  90620. EffectLayer.prototype.render = function () {
  90621. var currentEffect = this._mergeEffect;
  90622. // Check
  90623. if (!currentEffect.isReady())
  90624. return;
  90625. for (var i = 0; i < this._postProcesses.length; i++) {
  90626. if (!this._postProcesses[i].isReady()) {
  90627. return;
  90628. }
  90629. }
  90630. var engine = this._scene.getEngine();
  90631. this.onBeforeComposeObservable.notifyObservers(this);
  90632. // Render
  90633. engine.enableEffect(currentEffect);
  90634. engine.setState(false);
  90635. // VBOs
  90636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90637. // Cache
  90638. var previousAlphaMode = engine.getAlphaMode();
  90639. // Go Blend.
  90640. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90641. // Blends the map on the main canvas.
  90642. this._internalRender(currentEffect);
  90643. // Restore Alpha
  90644. engine.setAlphaMode(previousAlphaMode);
  90645. this.onAfterComposeObservable.notifyObservers(this);
  90646. // Handle size changes.
  90647. var size = this._mainTexture.getSize();
  90648. this._setMainTextureSize();
  90649. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90650. // Recreate RTT and post processes on size change.
  90651. this.onSizeChangedObservable.notifyObservers(this);
  90652. this._disposeTextureAndPostProcesses();
  90653. this._createMainTexture();
  90654. this._createTextureAndPostProcesses();
  90655. }
  90656. };
  90657. /**
  90658. * Determine if a given mesh will be used in the current effect.
  90659. * @param mesh mesh to test
  90660. * @returns true if the mesh will be used
  90661. */
  90662. EffectLayer.prototype.hasMesh = function (mesh) {
  90663. return true;
  90664. };
  90665. /**
  90666. * Returns true if the layer contains information to display, otherwise false.
  90667. * @returns true if the glow layer should be rendered
  90668. */
  90669. EffectLayer.prototype.shouldRender = function () {
  90670. return this.isEnabled && this._shouldRender;
  90671. };
  90672. /**
  90673. * Returns true if the mesh should render, otherwise false.
  90674. * @param mesh The mesh to render
  90675. * @returns true if it should render otherwise false
  90676. */
  90677. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90678. return true;
  90679. };
  90680. /**
  90681. * Returns true if the mesh should render, otherwise false.
  90682. * @param mesh The mesh to render
  90683. * @returns true if it should render otherwise false
  90684. */
  90685. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90686. return true;
  90687. };
  90688. /**
  90689. * Renders the submesh passed in parameter to the generation map.
  90690. */
  90691. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90692. var _this = this;
  90693. if (!this.shouldRender()) {
  90694. return;
  90695. }
  90696. var material = subMesh.getMaterial();
  90697. var mesh = subMesh.getRenderingMesh();
  90698. var scene = this._scene;
  90699. var engine = scene.getEngine();
  90700. if (!material) {
  90701. return;
  90702. }
  90703. // Do not block in blend mode.
  90704. if (material.needAlphaBlendingForMesh(mesh)) {
  90705. return;
  90706. }
  90707. // Culling
  90708. engine.setState(material.backFaceCulling);
  90709. // Managing instances
  90710. var batch = mesh._getInstancesRenderList(subMesh._id);
  90711. if (batch.mustReturn) {
  90712. return;
  90713. }
  90714. // Early Exit per mesh
  90715. if (!this._shouldRenderMesh(mesh)) {
  90716. return;
  90717. }
  90718. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90719. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90720. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90721. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90722. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90723. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90724. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90725. // Alpha test
  90726. if (material && material.needAlphaTesting()) {
  90727. var alphaTexture = material.getAlphaTestTexture();
  90728. if (alphaTexture) {
  90729. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90730. var textureMatrix = alphaTexture.getTextureMatrix();
  90731. if (textureMatrix) {
  90732. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90733. }
  90734. }
  90735. }
  90736. // Glow emissive only
  90737. if (this._emissiveTextureAndColor.texture) {
  90738. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90739. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90740. }
  90741. // Bones
  90742. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90743. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90744. }
  90745. // Morph targets
  90746. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90747. // Draw
  90748. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90749. }
  90750. else {
  90751. // Need to reset refresh rate of the shadowMap
  90752. this._mainTexture.resetRefreshCounter();
  90753. }
  90754. };
  90755. /**
  90756. * Rebuild the required buffers.
  90757. * @ignore Internal use only.
  90758. */
  90759. EffectLayer.prototype._rebuild = function () {
  90760. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90761. if (vb) {
  90762. vb._rebuild();
  90763. }
  90764. this._generateIndexBuffer();
  90765. };
  90766. /**
  90767. * Dispose only the render target textures and post process.
  90768. */
  90769. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90770. this._mainTexture.dispose();
  90771. for (var i = 0; i < this._postProcesses.length; i++) {
  90772. if (this._postProcesses[i]) {
  90773. this._postProcesses[i].dispose();
  90774. }
  90775. }
  90776. this._postProcesses = [];
  90777. for (var i = 0; i < this._textures.length; i++) {
  90778. if (this._textures[i]) {
  90779. this._textures[i].dispose();
  90780. }
  90781. }
  90782. this._textures = [];
  90783. };
  90784. /**
  90785. * Dispose the highlight layer and free resources.
  90786. */
  90787. EffectLayer.prototype.dispose = function () {
  90788. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90789. if (vertexBuffer) {
  90790. vertexBuffer.dispose();
  90791. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90792. }
  90793. if (this._indexBuffer) {
  90794. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90795. this._indexBuffer = null;
  90796. }
  90797. // Clean textures and post processes
  90798. this._disposeTextureAndPostProcesses();
  90799. // Remove from scene
  90800. var index = this._scene.effectLayers.indexOf(this, 0);
  90801. if (index > -1) {
  90802. this._scene.effectLayers.splice(index, 1);
  90803. }
  90804. // Callback
  90805. this.onDisposeObservable.notifyObservers(this);
  90806. this.onDisposeObservable.clear();
  90807. this.onBeforeRenderMainTextureObservable.clear();
  90808. this.onBeforeComposeObservable.clear();
  90809. this.onAfterComposeObservable.clear();
  90810. this.onSizeChangedObservable.clear();
  90811. };
  90812. /**
  90813. * Gets the class name of the effect layer
  90814. * @returns the string with the class name of the effect layer
  90815. */
  90816. EffectLayer.prototype.getClassName = function () {
  90817. return "EffectLayer";
  90818. };
  90819. /**
  90820. * Creates an effect layer from parsed effect layer data
  90821. * @param parsedEffectLayer defines effect layer data
  90822. * @param scene defines the current scene
  90823. * @param rootUrl defines the root URL containing the effect layer information
  90824. * @returns a parsed effect Layer
  90825. */
  90826. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  90827. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  90828. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  90829. };
  90830. __decorate([
  90831. BABYLON.serialize()
  90832. ], EffectLayer.prototype, "name", void 0);
  90833. __decorate([
  90834. BABYLON.serializeAsColor4()
  90835. ], EffectLayer.prototype, "neutralColor", void 0);
  90836. __decorate([
  90837. BABYLON.serialize()
  90838. ], EffectLayer.prototype, "isEnabled", void 0);
  90839. __decorate([
  90840. BABYLON.serializeAsCameraReference()
  90841. ], EffectLayer.prototype, "camera", null);
  90842. return EffectLayer;
  90843. }());
  90844. BABYLON.EffectLayer = EffectLayer;
  90845. })(BABYLON || (BABYLON = {}));
  90846. //# sourceMappingURL=babylon.effectLayer.js.map
  90847. var BABYLON;
  90848. (function (BABYLON) {
  90849. /**
  90850. * Special Glow Blur post process only blurring the alpha channel
  90851. * It enforces keeping the most luminous color in the color channel.
  90852. */
  90853. var GlowBlurPostProcess = /** @class */ (function (_super) {
  90854. __extends(GlowBlurPostProcess, _super);
  90855. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  90856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  90857. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  90858. _this.direction = direction;
  90859. _this.kernel = kernel;
  90860. _this.onApplyObservable.add(function (effect) {
  90861. effect.setFloat2("screenSize", _this.width, _this.height);
  90862. effect.setVector2("direction", _this.direction);
  90863. effect.setFloat("blurWidth", _this.kernel);
  90864. });
  90865. return _this;
  90866. }
  90867. return GlowBlurPostProcess;
  90868. }(BABYLON.PostProcess));
  90869. /**
  90870. * The highlight layer Helps adding a glow effect around a mesh.
  90871. *
  90872. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  90873. * glowy meshes to your scene.
  90874. *
  90875. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  90876. */
  90877. var HighlightLayer = /** @class */ (function (_super) {
  90878. __extends(HighlightLayer, _super);
  90879. /**
  90880. * Instantiates a new highlight Layer and references it to the scene..
  90881. * @param name The name of the layer
  90882. * @param scene The scene to use the layer in
  90883. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  90884. */
  90885. function HighlightLayer(name, scene, options) {
  90886. var _this = _super.call(this, name, scene) || this;
  90887. _this.name = name;
  90888. /**
  90889. * Specifies whether or not the inner glow is ACTIVE in the layer.
  90890. */
  90891. _this.innerGlow = true;
  90892. /**
  90893. * Specifies whether or not the outer glow is ACTIVE in the layer.
  90894. */
  90895. _this.outerGlow = true;
  90896. /**
  90897. * An event triggered when the highlight layer is being blurred.
  90898. */
  90899. _this.onBeforeBlurObservable = new BABYLON.Observable();
  90900. /**
  90901. * An event triggered when the highlight layer has been blurred.
  90902. */
  90903. _this.onAfterBlurObservable = new BABYLON.Observable();
  90904. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  90905. _this._meshes = {};
  90906. _this._excludedMeshes = {};
  90907. _this.neutralColor = HighlightLayer.NeutralColor;
  90908. // Warn on stencil
  90909. if (!_this._engine.isStencilEnable) {
  90910. 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 }");
  90911. }
  90912. // Adapt options
  90913. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90914. // Initialize the layer
  90915. _this._init({
  90916. alphaBlendingMode: _this._options.alphaBlendingMode,
  90917. camera: _this._options.camera,
  90918. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  90919. mainTextureRatio: _this._options.mainTextureRatio
  90920. });
  90921. // Do not render as long as no meshes have been added
  90922. _this._shouldRender = false;
  90923. return _this;
  90924. }
  90925. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  90926. /**
  90927. * Gets the horizontal size of the blur.
  90928. */
  90929. get: function () {
  90930. return this._horizontalBlurPostprocess.kernel;
  90931. },
  90932. /**
  90933. * Specifies the horizontal size of the blur.
  90934. */
  90935. set: function (value) {
  90936. this._horizontalBlurPostprocess.kernel = value;
  90937. },
  90938. enumerable: true,
  90939. configurable: true
  90940. });
  90941. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  90942. /**
  90943. * Gets the vertical size of the blur.
  90944. */
  90945. get: function () {
  90946. return this._verticalBlurPostprocess.kernel;
  90947. },
  90948. /**
  90949. * Specifies the vertical size of the blur.
  90950. */
  90951. set: function (value) {
  90952. this._verticalBlurPostprocess.kernel = value;
  90953. },
  90954. enumerable: true,
  90955. configurable: true
  90956. });
  90957. /**
  90958. * Get the effect name of the layer.
  90959. * @return The effect name
  90960. */
  90961. HighlightLayer.prototype.getEffectName = function () {
  90962. return HighlightLayer.EffectName;
  90963. };
  90964. /**
  90965. * Create the merge effect. This is the shader use to blit the information back
  90966. * to the main canvas at the end of the scene rendering.
  90967. */
  90968. HighlightLayer.prototype._createMergeEffect = function () {
  90969. // Effect
  90970. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  90971. };
  90972. /**
  90973. * Creates the render target textures and post processes used in the highlight layer.
  90974. */
  90975. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  90976. var _this = this;
  90977. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  90978. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  90979. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  90980. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  90981. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  90982. width: blurTextureWidth,
  90983. height: blurTextureHeight
  90984. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  90985. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90986. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90987. this._blurTexture.anisotropicFilteringLevel = 16;
  90988. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  90989. this._blurTexture.renderParticles = false;
  90990. this._blurTexture.ignoreCameraViewport = true;
  90991. this._textures = [this._blurTexture];
  90992. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  90993. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90994. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  90995. effect.setTexture("textureSampler", _this._mainTexture);
  90996. });
  90997. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  90998. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  90999. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91000. });
  91001. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91002. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91003. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91004. });
  91005. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91006. }
  91007. else {
  91008. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91009. width: blurTextureWidth,
  91010. height: blurTextureHeight
  91011. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91012. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91013. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91014. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91015. effect.setTexture("textureSampler", _this._mainTexture);
  91016. });
  91017. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91018. width: blurTextureWidth,
  91019. height: blurTextureHeight
  91020. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91021. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91022. }
  91023. this._mainTexture.onAfterUnbindObservable.add(function () {
  91024. _this.onBeforeBlurObservable.notifyObservers(_this);
  91025. var internalTexture = _this._blurTexture.getInternalTexture();
  91026. if (internalTexture) {
  91027. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91028. }
  91029. _this.onAfterBlurObservable.notifyObservers(_this);
  91030. });
  91031. // Prevent autoClear.
  91032. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91033. };
  91034. /**
  91035. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91036. */
  91037. HighlightLayer.prototype.needStencil = function () {
  91038. return true;
  91039. };
  91040. /**
  91041. * Checks for the readiness of the element composing the layer.
  91042. * @param subMesh the mesh to check for
  91043. * @param useInstances specify wether or not to use instances to render the mesh
  91044. * @param emissiveTexture the associated emissive texture used to generate the glow
  91045. * @return true if ready otherwise, false
  91046. */
  91047. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91048. var material = subMesh.getMaterial();
  91049. var mesh = subMesh.getRenderingMesh();
  91050. if (!material || !mesh || !this._meshes) {
  91051. return false;
  91052. }
  91053. var emissiveTexture = null;
  91054. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91055. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91056. emissiveTexture = material.emissiveTexture;
  91057. }
  91058. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91059. };
  91060. /**
  91061. * Implementation specific of rendering the generating effect on the main canvas.
  91062. * @param effect The effect used to render through
  91063. */
  91064. HighlightLayer.prototype._internalRender = function (effect) {
  91065. // Texture
  91066. effect.setTexture("textureSampler", this._blurTexture);
  91067. // Cache
  91068. var engine = this._engine;
  91069. var previousStencilBuffer = engine.getStencilBuffer();
  91070. var previousStencilFunction = engine.getStencilFunction();
  91071. var previousStencilMask = engine.getStencilMask();
  91072. var previousStencilOperationPass = engine.getStencilOperationPass();
  91073. var previousStencilOperationFail = engine.getStencilOperationFail();
  91074. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91075. var previousStencilReference = engine.getStencilFunctionReference();
  91076. // Stencil operations
  91077. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91078. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91079. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91080. // Draw order
  91081. engine.setStencilMask(0x00);
  91082. engine.setStencilBuffer(true);
  91083. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91084. // 2 passes inner outer
  91085. if (this.outerGlow) {
  91086. effect.setFloat("offset", 0);
  91087. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91088. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91089. }
  91090. if (this.innerGlow) {
  91091. effect.setFloat("offset", 1);
  91092. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91093. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91094. }
  91095. // Restore Cache
  91096. engine.setStencilFunction(previousStencilFunction);
  91097. engine.setStencilMask(previousStencilMask);
  91098. engine.setStencilBuffer(previousStencilBuffer);
  91099. engine.setStencilOperationPass(previousStencilOperationPass);
  91100. engine.setStencilOperationFail(previousStencilOperationFail);
  91101. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91102. engine.setStencilFunctionReference(previousStencilReference);
  91103. };
  91104. /**
  91105. * Returns true if the layer contains information to display, otherwise false.
  91106. */
  91107. HighlightLayer.prototype.shouldRender = function () {
  91108. if (_super.prototype.shouldRender.call(this)) {
  91109. return this._meshes ? true : false;
  91110. }
  91111. return false;
  91112. };
  91113. /**
  91114. * Returns true if the mesh should render, otherwise false.
  91115. * @param mesh The mesh to render
  91116. * @returns true if it should render otherwise false
  91117. */
  91118. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91119. // Excluded Mesh
  91120. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91121. return false;
  91122. }
  91123. ;
  91124. return true;
  91125. };
  91126. /**
  91127. * Sets the required values for both the emissive texture and and the main color.
  91128. */
  91129. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91130. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91131. if (highlightLayerMesh) {
  91132. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91133. }
  91134. else {
  91135. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91136. }
  91137. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91138. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91139. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91140. }
  91141. else {
  91142. this._emissiveTextureAndColor.texture = null;
  91143. }
  91144. };
  91145. /**
  91146. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91147. * @param mesh The mesh to exclude from the highlight layer
  91148. */
  91149. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91150. if (!this._excludedMeshes) {
  91151. return;
  91152. }
  91153. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91154. if (!meshExcluded) {
  91155. this._excludedMeshes[mesh.uniqueId] = {
  91156. mesh: mesh,
  91157. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91158. mesh.getEngine().setStencilBuffer(false);
  91159. }),
  91160. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91161. mesh.getEngine().setStencilBuffer(true);
  91162. }),
  91163. };
  91164. }
  91165. };
  91166. /**
  91167. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91168. * @param mesh The mesh to highlight
  91169. */
  91170. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91171. if (!this._excludedMeshes) {
  91172. return;
  91173. }
  91174. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91175. if (meshExcluded) {
  91176. if (meshExcluded.beforeRender) {
  91177. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91178. }
  91179. if (meshExcluded.afterRender) {
  91180. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91181. }
  91182. }
  91183. this._excludedMeshes[mesh.uniqueId] = null;
  91184. };
  91185. /**
  91186. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91187. * @param mesh mesh to test
  91188. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91189. */
  91190. HighlightLayer.prototype.hasMesh = function (mesh) {
  91191. if (!this._meshes) {
  91192. return false;
  91193. }
  91194. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91195. };
  91196. /**
  91197. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91198. * @param mesh The mesh to highlight
  91199. * @param color The color of the highlight
  91200. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91201. */
  91202. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91203. var _this = this;
  91204. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91205. if (!this._meshes) {
  91206. return;
  91207. }
  91208. var meshHighlight = this._meshes[mesh.uniqueId];
  91209. if (meshHighlight) {
  91210. meshHighlight.color = color;
  91211. }
  91212. else {
  91213. this._meshes[mesh.uniqueId] = {
  91214. mesh: mesh,
  91215. color: color,
  91216. // Lambda required for capture due to Observable this context
  91217. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91218. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91219. _this._defaultStencilReference(mesh);
  91220. }
  91221. else {
  91222. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91223. }
  91224. }),
  91225. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91226. glowEmissiveOnly: glowEmissiveOnly
  91227. };
  91228. }
  91229. this._shouldRender = true;
  91230. };
  91231. /**
  91232. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91233. * @param mesh The mesh to highlight
  91234. */
  91235. HighlightLayer.prototype.removeMesh = function (mesh) {
  91236. if (!this._meshes) {
  91237. return;
  91238. }
  91239. var meshHighlight = this._meshes[mesh.uniqueId];
  91240. if (meshHighlight) {
  91241. if (meshHighlight.observerHighlight) {
  91242. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91243. }
  91244. if (meshHighlight.observerDefault) {
  91245. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91246. }
  91247. delete this._meshes[mesh.uniqueId];
  91248. }
  91249. this._shouldRender = false;
  91250. for (var meshHighlightToCheck in this._meshes) {
  91251. if (this._meshes[meshHighlightToCheck]) {
  91252. this._shouldRender = true;
  91253. break;
  91254. }
  91255. }
  91256. };
  91257. /**
  91258. * Force the stencil to the normal expected value for none glowing parts
  91259. */
  91260. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91261. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91262. };
  91263. /**
  91264. * Free any resources and references associated to a mesh.
  91265. * Internal use
  91266. * @param mesh The mesh to free.
  91267. */
  91268. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91269. this.removeMesh(mesh);
  91270. this.removeExcludedMesh(mesh);
  91271. };
  91272. /**
  91273. * Dispose the highlight layer and free resources.
  91274. */
  91275. HighlightLayer.prototype.dispose = function () {
  91276. if (this._meshes) {
  91277. // Clean mesh references
  91278. for (var id in this._meshes) {
  91279. var meshHighlight = this._meshes[id];
  91280. if (meshHighlight && meshHighlight.mesh) {
  91281. if (meshHighlight.observerHighlight) {
  91282. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91283. }
  91284. if (meshHighlight.observerDefault) {
  91285. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91286. }
  91287. }
  91288. }
  91289. this._meshes = null;
  91290. }
  91291. if (this._excludedMeshes) {
  91292. for (var id in this._excludedMeshes) {
  91293. var meshHighlight = this._excludedMeshes[id];
  91294. if (meshHighlight) {
  91295. if (meshHighlight.beforeRender) {
  91296. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91297. }
  91298. if (meshHighlight.afterRender) {
  91299. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91300. }
  91301. }
  91302. }
  91303. this._excludedMeshes = null;
  91304. }
  91305. _super.prototype.dispose.call(this);
  91306. };
  91307. /**
  91308. * Gets the class name of the effect layer
  91309. * @returns the string with the class name of the effect layer
  91310. */
  91311. HighlightLayer.prototype.getClassName = function () {
  91312. return "HighlightLayer";
  91313. };
  91314. /**
  91315. * Serializes this Highlight layer
  91316. * @returns a serialized Highlight layer object
  91317. */
  91318. HighlightLayer.prototype.serialize = function () {
  91319. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91320. serializationObject.customType = "BABYLON.HighlightLayer";
  91321. // Highlighted meshes
  91322. serializationObject.meshes = [];
  91323. if (this._meshes) {
  91324. for (var m in this._meshes) {
  91325. var mesh = this._meshes[m];
  91326. if (mesh) {
  91327. serializationObject.meshes.push({
  91328. glowEmissiveOnly: mesh.glowEmissiveOnly,
  91329. color: mesh.color.asArray(),
  91330. meshId: mesh.mesh.id
  91331. });
  91332. }
  91333. }
  91334. }
  91335. // Excluded meshes
  91336. serializationObject.excludedMeshes = [];
  91337. if (this._excludedMeshes) {
  91338. for (var e in this._excludedMeshes) {
  91339. var excludedMesh = this._excludedMeshes[e];
  91340. if (excludedMesh) {
  91341. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  91342. }
  91343. }
  91344. }
  91345. return serializationObject;
  91346. };
  91347. /**
  91348. * Creates a Highlight layer from parsed Highlight layer data
  91349. * @param parsedHightlightLayer defines the Highlight layer data
  91350. * @param scene defines the current scene
  91351. * @param rootUrl defines the root URL containing the Highlight layer information
  91352. * @returns a parsed Highlight layer
  91353. */
  91354. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  91355. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  91356. var index;
  91357. // Excluded meshes
  91358. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  91359. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  91360. if (mesh) {
  91361. hl.addExcludedMesh(mesh);
  91362. }
  91363. }
  91364. // Included meshes
  91365. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  91366. var highlightedMesh = parsedHightlightLayer.meshes[index];
  91367. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  91368. if (mesh) {
  91369. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  91370. }
  91371. }
  91372. return hl;
  91373. };
  91374. /**
  91375. * Effect Name of the highlight layer.
  91376. */
  91377. HighlightLayer.EffectName = "HighlightLayer";
  91378. /**
  91379. * The neutral color used during the preparation of the glow effect.
  91380. * This is black by default as the blend operation is a blend operation.
  91381. */
  91382. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  91383. /**
  91384. * Stencil value used for glowing meshes.
  91385. */
  91386. HighlightLayer.GlowingMeshStencilReference = 0x02;
  91387. /**
  91388. * Stencil value used for the other meshes in the scene.
  91389. */
  91390. HighlightLayer.NormalMeshStencilReference = 0x01;
  91391. __decorate([
  91392. BABYLON.serialize()
  91393. ], HighlightLayer.prototype, "innerGlow", void 0);
  91394. __decorate([
  91395. BABYLON.serialize()
  91396. ], HighlightLayer.prototype, "outerGlow", void 0);
  91397. __decorate([
  91398. BABYLON.serialize()
  91399. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  91400. __decorate([
  91401. BABYLON.serialize()
  91402. ], HighlightLayer.prototype, "blurVerticalSize", null);
  91403. __decorate([
  91404. BABYLON.serialize("options")
  91405. ], HighlightLayer.prototype, "_options", void 0);
  91406. return HighlightLayer;
  91407. }(BABYLON.EffectLayer));
  91408. BABYLON.HighlightLayer = HighlightLayer;
  91409. })(BABYLON || (BABYLON = {}));
  91410. //# sourceMappingURL=babylon.highlightLayer.js.map
  91411. var BABYLON;
  91412. (function (BABYLON) {
  91413. /**
  91414. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  91415. *
  91416. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91417. * glowy meshes to your scene.
  91418. *
  91419. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  91420. */
  91421. var GlowLayer = /** @class */ (function (_super) {
  91422. __extends(GlowLayer, _super);
  91423. /**
  91424. * Instantiates a new glow Layer and references it to the scene.
  91425. * @param name The name of the layer
  91426. * @param scene The scene to use the layer in
  91427. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  91428. */
  91429. function GlowLayer(name, scene, options) {
  91430. var _this = _super.call(this, name, scene) || this;
  91431. _this._intensity = 1.0;
  91432. _this._includedOnlyMeshes = [];
  91433. _this._excludedMeshes = [];
  91434. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  91435. // Adapt options
  91436. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  91437. // Initialize the layer
  91438. _this._init({
  91439. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  91440. camera: _this._options.camera,
  91441. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91442. mainTextureRatio: _this._options.mainTextureRatio
  91443. });
  91444. return _this;
  91445. }
  91446. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  91447. /**
  91448. * Gets the kernel size of the blur.
  91449. */
  91450. get: function () {
  91451. return this._horizontalBlurPostprocess1.kernel;
  91452. },
  91453. /**
  91454. * Sets the kernel size of the blur.
  91455. */
  91456. set: function (value) {
  91457. this._horizontalBlurPostprocess1.kernel = value;
  91458. this._verticalBlurPostprocess1.kernel = value;
  91459. this._horizontalBlurPostprocess2.kernel = value;
  91460. this._verticalBlurPostprocess2.kernel = value;
  91461. },
  91462. enumerable: true,
  91463. configurable: true
  91464. });
  91465. Object.defineProperty(GlowLayer.prototype, "intensity", {
  91466. /**
  91467. * Gets the glow intensity.
  91468. */
  91469. get: function () {
  91470. return this._intensity;
  91471. },
  91472. /**
  91473. * Sets the glow intensity.
  91474. */
  91475. set: function (value) {
  91476. this._intensity = value;
  91477. },
  91478. enumerable: true,
  91479. configurable: true
  91480. });
  91481. /**
  91482. * Get the effect name of the layer.
  91483. * @return The effect name
  91484. */
  91485. GlowLayer.prototype.getEffectName = function () {
  91486. return GlowLayer.EffectName;
  91487. };
  91488. /**
  91489. * Create the merge effect. This is the shader use to blit the information back
  91490. * to the main canvas at the end of the scene rendering.
  91491. */
  91492. GlowLayer.prototype._createMergeEffect = function () {
  91493. // Effect
  91494. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  91495. };
  91496. /**
  91497. * Creates the render target textures and post processes used in the glow layer.
  91498. */
  91499. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  91500. var _this = this;
  91501. var blurTextureWidth = this._mainTextureDesiredSize.width;
  91502. var blurTextureHeight = this._mainTextureDesiredSize.height;
  91503. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91504. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91505. var textureType = 0;
  91506. if (this._engine.getCaps().textureHalfFloatRender) {
  91507. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91508. }
  91509. else {
  91510. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91511. }
  91512. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  91513. width: blurTextureWidth,
  91514. height: blurTextureHeight
  91515. }, this._scene, false, true, textureType);
  91516. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91517. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91518. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91519. this._blurTexture1.renderParticles = false;
  91520. this._blurTexture1.ignoreCameraViewport = true;
  91521. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  91522. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  91523. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  91524. width: blurTextureWidth2,
  91525. height: blurTextureHeight2
  91526. }, this._scene, false, true, textureType);
  91527. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91528. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91529. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91530. this._blurTexture2.renderParticles = false;
  91531. this._blurTexture2.ignoreCameraViewport = true;
  91532. this._textures = [this._blurTexture1, this._blurTexture2];
  91533. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91534. width: blurTextureWidth,
  91535. height: blurTextureHeight
  91536. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91537. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  91538. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  91539. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  91540. effect.setTexture("textureSampler", _this._mainTexture);
  91541. });
  91542. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91543. width: blurTextureWidth,
  91544. height: blurTextureHeight
  91545. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91546. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91547. width: blurTextureWidth2,
  91548. height: blurTextureHeight2
  91549. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91550. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91551. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91552. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91553. effect.setTexture("textureSampler", _this._blurTexture1);
  91554. });
  91555. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91556. width: blurTextureWidth2,
  91557. height: blurTextureHeight2
  91558. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91559. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91560. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91561. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91562. this._mainTexture.samples = this._options.mainTextureSamples;
  91563. this._mainTexture.onAfterUnbindObservable.add(function () {
  91564. var internalTexture = _this._blurTexture1.getInternalTexture();
  91565. if (internalTexture) {
  91566. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91567. internalTexture = _this._blurTexture2.getInternalTexture();
  91568. if (internalTexture) {
  91569. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91570. }
  91571. }
  91572. });
  91573. // Prevent autoClear.
  91574. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91575. };
  91576. /**
  91577. * Checks for the readiness of the element composing the layer.
  91578. * @param subMesh the mesh to check for
  91579. * @param useInstances specify wether or not to use instances to render the mesh
  91580. * @param emissiveTexture the associated emissive texture used to generate the glow
  91581. * @return true if ready otherwise, false
  91582. */
  91583. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91584. var material = subMesh.getMaterial();
  91585. var mesh = subMesh.getRenderingMesh();
  91586. if (!material || !mesh) {
  91587. return false;
  91588. }
  91589. var emissiveTexture = material.emissiveTexture;
  91590. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91591. };
  91592. /**
  91593. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91594. */
  91595. GlowLayer.prototype.needStencil = function () {
  91596. return false;
  91597. };
  91598. /**
  91599. * Implementation specific of rendering the generating effect on the main canvas.
  91600. * @param effect The effect used to render through
  91601. */
  91602. GlowLayer.prototype._internalRender = function (effect) {
  91603. // Texture
  91604. effect.setTexture("textureSampler", this._blurTexture1);
  91605. effect.setTexture("textureSampler2", this._blurTexture2);
  91606. effect.setFloat("offset", this._intensity);
  91607. // Cache
  91608. var engine = this._engine;
  91609. var previousStencilBuffer = engine.getStencilBuffer();
  91610. // Draw order
  91611. engine.setStencilBuffer(false);
  91612. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91613. // Draw order
  91614. engine.setStencilBuffer(previousStencilBuffer);
  91615. };
  91616. /**
  91617. * Sets the required values for both the emissive texture and and the main color.
  91618. */
  91619. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91620. var textureLevel = 1.0;
  91621. if (this.customEmissiveTextureSelector) {
  91622. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91623. }
  91624. else {
  91625. if (material) {
  91626. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91627. if (this._emissiveTextureAndColor.texture) {
  91628. textureLevel = this._emissiveTextureAndColor.texture.level;
  91629. }
  91630. }
  91631. else {
  91632. this._emissiveTextureAndColor.texture = null;
  91633. }
  91634. }
  91635. if (this.customEmissiveColorSelector) {
  91636. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91637. }
  91638. else {
  91639. if (material.emissiveColor) {
  91640. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91641. }
  91642. else {
  91643. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91644. }
  91645. }
  91646. };
  91647. /**
  91648. * Returns true if the mesh should render, otherwise false.
  91649. * @param mesh The mesh to render
  91650. * @returns true if it should render otherwise false
  91651. */
  91652. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91653. return this.hasMesh(mesh);
  91654. };
  91655. /**
  91656. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91657. * @param mesh The mesh to exclude from the glow layer
  91658. */
  91659. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91660. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91661. this._excludedMeshes.push(mesh.uniqueId);
  91662. }
  91663. };
  91664. /**
  91665. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91666. * @param mesh The mesh to remove
  91667. */
  91668. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91669. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91670. if (index !== -1) {
  91671. this._excludedMeshes.splice(index, 1);
  91672. }
  91673. };
  91674. /**
  91675. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91676. * @param mesh The mesh to include in the glow layer
  91677. */
  91678. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91679. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91680. this._includedOnlyMeshes.push(mesh.uniqueId);
  91681. }
  91682. };
  91683. /**
  91684. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91685. * @param mesh The mesh to remove
  91686. */
  91687. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91688. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91689. if (index !== -1) {
  91690. this._includedOnlyMeshes.splice(index, 1);
  91691. }
  91692. };
  91693. /**
  91694. * Determine if a given mesh will be used in the glow layer
  91695. * @param mesh The mesh to test
  91696. * @returns true if the mesh will be highlighted by the current glow layer
  91697. */
  91698. GlowLayer.prototype.hasMesh = function (mesh) {
  91699. // Included Mesh
  91700. if (this._includedOnlyMeshes.length) {
  91701. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91702. }
  91703. ;
  91704. // Excluded Mesh
  91705. if (this._excludedMeshes.length) {
  91706. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91707. }
  91708. ;
  91709. return true;
  91710. };
  91711. /**
  91712. * Free any resources and references associated to a mesh.
  91713. * Internal use
  91714. * @param mesh The mesh to free.
  91715. */
  91716. GlowLayer.prototype._disposeMesh = function (mesh) {
  91717. this.removeIncludedOnlyMesh(mesh);
  91718. this.removeExcludedMesh(mesh);
  91719. };
  91720. /**
  91721. * Gets the class name of the effect layer
  91722. * @returns the string with the class name of the effect layer
  91723. */
  91724. GlowLayer.prototype.getClassName = function () {
  91725. return "GlowLayer";
  91726. };
  91727. /**
  91728. * Serializes this glow layer
  91729. * @returns a serialized glow layer object
  91730. */
  91731. GlowLayer.prototype.serialize = function () {
  91732. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91733. serializationObject.customType = "BABYLON.GlowLayer";
  91734. var index;
  91735. // Included meshes
  91736. serializationObject.includedMeshes = [];
  91737. if (this._includedOnlyMeshes.length) {
  91738. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91739. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91740. if (mesh) {
  91741. serializationObject.includedMeshes.push(mesh.id);
  91742. }
  91743. }
  91744. }
  91745. // Excluded meshes
  91746. serializationObject.excludedMeshes = [];
  91747. if (this._excludedMeshes.length) {
  91748. for (index = 0; index < this._excludedMeshes.length; index++) {
  91749. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91750. if (mesh) {
  91751. serializationObject.excludedMeshes.push(mesh.id);
  91752. }
  91753. }
  91754. }
  91755. return serializationObject;
  91756. };
  91757. /**
  91758. * Creates a Glow Layer from parsed glow layer data
  91759. * @param parsedGlowLayer defines glow layer data
  91760. * @param scene defines the current scene
  91761. * @param rootUrl defines the root URL containing the glow layer information
  91762. * @returns a parsed Glow Layer
  91763. */
  91764. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91765. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91766. var index;
  91767. // Excluded meshes
  91768. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91769. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91770. if (mesh) {
  91771. gl.addExcludedMesh(mesh);
  91772. }
  91773. }
  91774. // Included meshes
  91775. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91776. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91777. if (mesh) {
  91778. gl.addIncludedOnlyMesh(mesh);
  91779. }
  91780. }
  91781. return gl;
  91782. };
  91783. /**
  91784. * Effect Name of the layer.
  91785. */
  91786. GlowLayer.EffectName = "GlowLayer";
  91787. /**
  91788. * The default blur kernel size used for the glow.
  91789. */
  91790. GlowLayer.DefaultBlurKernelSize = 32;
  91791. /**
  91792. * The default texture size ratio used for the glow.
  91793. */
  91794. GlowLayer.DefaultTextureRatio = 0.5;
  91795. __decorate([
  91796. BABYLON.serialize()
  91797. ], GlowLayer.prototype, "blurKernelSize", null);
  91798. __decorate([
  91799. BABYLON.serialize()
  91800. ], GlowLayer.prototype, "intensity", null);
  91801. __decorate([
  91802. BABYLON.serialize("options")
  91803. ], GlowLayer.prototype, "_options", void 0);
  91804. return GlowLayer;
  91805. }(BABYLON.EffectLayer));
  91806. BABYLON.GlowLayer = GlowLayer;
  91807. })(BABYLON || (BABYLON = {}));
  91808. //# sourceMappingURL=babylon.glowLayer.js.map
  91809. var BABYLON;
  91810. (function (BABYLON) {
  91811. /**
  91812. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  91813. */
  91814. var AssetTaskState;
  91815. (function (AssetTaskState) {
  91816. /**
  91817. * Initialization
  91818. */
  91819. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  91820. /**
  91821. * Running
  91822. */
  91823. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  91824. /**
  91825. * Done
  91826. */
  91827. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  91828. /**
  91829. * Error
  91830. */
  91831. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  91832. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  91833. /**
  91834. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  91835. */
  91836. var AbstractAssetTask = /** @class */ (function () {
  91837. /**
  91838. * Creates a new {BABYLON.AssetsManager}
  91839. * @param name defines the name of the task
  91840. */
  91841. function AbstractAssetTask(
  91842. /**
  91843. * Task name
  91844. */ name) {
  91845. this.name = name;
  91846. this._isCompleted = false;
  91847. this._taskState = AssetTaskState.INIT;
  91848. }
  91849. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  91850. /**
  91851. * Get if the task is completed
  91852. */
  91853. get: function () {
  91854. return this._isCompleted;
  91855. },
  91856. enumerable: true,
  91857. configurable: true
  91858. });
  91859. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  91860. /**
  91861. * Gets the current state of the task
  91862. */
  91863. get: function () {
  91864. return this._taskState;
  91865. },
  91866. enumerable: true,
  91867. configurable: true
  91868. });
  91869. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  91870. /**
  91871. * Gets the current error object (if task is in error)
  91872. */
  91873. get: function () {
  91874. return this._errorObject;
  91875. },
  91876. enumerable: true,
  91877. configurable: true
  91878. });
  91879. /**
  91880. * Internal only
  91881. * @ignore
  91882. */
  91883. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  91884. if (this._errorObject) {
  91885. return;
  91886. }
  91887. this._errorObject = {
  91888. message: message,
  91889. exception: exception
  91890. };
  91891. };
  91892. /**
  91893. * Execute the current task
  91894. * @param scene defines the scene where you want your assets to be loaded
  91895. * @param onSuccess is a callback called when the task is successfully executed
  91896. * @param onError is a callback called if an error occurs
  91897. */
  91898. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  91899. var _this = this;
  91900. this._taskState = AssetTaskState.RUNNING;
  91901. this.runTask(scene, function () {
  91902. _this.onDoneCallback(onSuccess, onError);
  91903. }, function (msg, exception) {
  91904. _this.onErrorCallback(onError, msg, exception);
  91905. });
  91906. };
  91907. /**
  91908. * Execute the current task
  91909. * @param scene defines the scene where you want your assets to be loaded
  91910. * @param onSuccess is a callback called when the task is successfully executed
  91911. * @param onError is a callback called if an error occurs
  91912. */
  91913. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  91914. throw new Error("runTask is not implemented");
  91915. };
  91916. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  91917. this._taskState = AssetTaskState.ERROR;
  91918. this._errorObject = {
  91919. message: message,
  91920. exception: exception
  91921. };
  91922. if (this.onError) {
  91923. this.onError(this, message, exception);
  91924. }
  91925. onError();
  91926. };
  91927. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  91928. try {
  91929. this._taskState = AssetTaskState.DONE;
  91930. this._isCompleted = true;
  91931. if (this.onSuccess) {
  91932. this.onSuccess(this);
  91933. }
  91934. onSuccess();
  91935. }
  91936. catch (e) {
  91937. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  91938. }
  91939. };
  91940. return AbstractAssetTask;
  91941. }());
  91942. BABYLON.AbstractAssetTask = AbstractAssetTask;
  91943. /**
  91944. * Class used to share progress information about assets loading
  91945. */
  91946. var AssetsProgressEvent = /** @class */ (function () {
  91947. /**
  91948. * Creates a {BABYLON.AssetsProgressEvent}
  91949. * @param remainingCount defines the number of remaining tasks to process
  91950. * @param totalCount defines the total number of tasks
  91951. * @param task defines the task that was just processed
  91952. */
  91953. function AssetsProgressEvent(remainingCount, totalCount, task) {
  91954. this.remainingCount = remainingCount;
  91955. this.totalCount = totalCount;
  91956. this.task = task;
  91957. }
  91958. return AssetsProgressEvent;
  91959. }());
  91960. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  91961. /**
  91962. * Define a task used by {BABYLON.AssetsManager} to load meshes
  91963. */
  91964. var MeshAssetTask = /** @class */ (function (_super) {
  91965. __extends(MeshAssetTask, _super);
  91966. /**
  91967. * Creates a new {BABYLON.MeshAssetTask}
  91968. * @param name defines the name of the task
  91969. * @param meshesNames defines the list of mesh's names you want to load
  91970. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  91971. * @param sceneFilename defines the filename of the scene to load from
  91972. */
  91973. function MeshAssetTask(
  91974. /**
  91975. * Defines the name of the task
  91976. */
  91977. name,
  91978. /**
  91979. * Defines the list of mesh's names you want to load
  91980. */
  91981. meshesNames,
  91982. /**
  91983. * Defines the root url to use as a base to load your meshes and associated resources
  91984. */
  91985. rootUrl,
  91986. /**
  91987. * Defines the filename of the scene to load from
  91988. */
  91989. sceneFilename) {
  91990. var _this = _super.call(this, name) || this;
  91991. _this.name = name;
  91992. _this.meshesNames = meshesNames;
  91993. _this.rootUrl = rootUrl;
  91994. _this.sceneFilename = sceneFilename;
  91995. return _this;
  91996. }
  91997. /**
  91998. * Execute the current task
  91999. * @param scene defines the scene where you want your assets to be loaded
  92000. * @param onSuccess is a callback called when the task is successfully executed
  92001. * @param onError is a callback called if an error occurs
  92002. */
  92003. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92004. var _this = this;
  92005. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92006. _this.loadedMeshes = meshes;
  92007. _this.loadedParticleSystems = particleSystems;
  92008. _this.loadedSkeletons = skeletons;
  92009. onSuccess();
  92010. }, null, function (scene, message, exception) {
  92011. onError(message, exception);
  92012. });
  92013. };
  92014. return MeshAssetTask;
  92015. }(AbstractAssetTask));
  92016. BABYLON.MeshAssetTask = MeshAssetTask;
  92017. /**
  92018. * Define a task used by {BABYLON.AssetsManager} to load text content
  92019. */
  92020. var TextFileAssetTask = /** @class */ (function (_super) {
  92021. __extends(TextFileAssetTask, _super);
  92022. /**
  92023. * Creates a new TextFileAssetTask object
  92024. * @param name defines the name of the task
  92025. * @param url defines the location of the file to load
  92026. */
  92027. function TextFileAssetTask(
  92028. /**
  92029. * Defines the name of the task
  92030. */
  92031. name,
  92032. /**
  92033. * Defines the location of the file to load
  92034. */
  92035. url) {
  92036. var _this = _super.call(this, name) || this;
  92037. _this.name = name;
  92038. _this.url = url;
  92039. return _this;
  92040. }
  92041. /**
  92042. * Execute the current task
  92043. * @param scene defines the scene where you want your assets to be loaded
  92044. * @param onSuccess is a callback called when the task is successfully executed
  92045. * @param onError is a callback called if an error occurs
  92046. */
  92047. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92048. var _this = this;
  92049. scene._loadFile(this.url, function (data) {
  92050. _this.text = data;
  92051. onSuccess();
  92052. }, undefined, false, false, function (request, exception) {
  92053. if (request) {
  92054. onError(request.status + " " + request.statusText, exception);
  92055. }
  92056. });
  92057. };
  92058. return TextFileAssetTask;
  92059. }(AbstractAssetTask));
  92060. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92061. /**
  92062. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92063. */
  92064. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92065. __extends(BinaryFileAssetTask, _super);
  92066. /**
  92067. * Creates a new BinaryFileAssetTask object
  92068. * @param name defines the name of the new task
  92069. * @param url defines the location of the file to load
  92070. */
  92071. function BinaryFileAssetTask(
  92072. /**
  92073. * Defines the name of the task
  92074. */
  92075. name,
  92076. /**
  92077. * Defines the location of the file to load
  92078. */
  92079. url) {
  92080. var _this = _super.call(this, name) || this;
  92081. _this.name = name;
  92082. _this.url = url;
  92083. return _this;
  92084. }
  92085. /**
  92086. * Execute the current task
  92087. * @param scene defines the scene where you want your assets to be loaded
  92088. * @param onSuccess is a callback called when the task is successfully executed
  92089. * @param onError is a callback called if an error occurs
  92090. */
  92091. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92092. var _this = this;
  92093. scene._loadFile(this.url, function (data) {
  92094. _this.data = data;
  92095. onSuccess();
  92096. }, undefined, true, true, function (request, exception) {
  92097. if (request) {
  92098. onError(request.status + " " + request.statusText, exception);
  92099. }
  92100. });
  92101. };
  92102. return BinaryFileAssetTask;
  92103. }(AbstractAssetTask));
  92104. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92105. /**
  92106. * Define a task used by {BABYLON.AssetsManager} to load images
  92107. */
  92108. var ImageAssetTask = /** @class */ (function (_super) {
  92109. __extends(ImageAssetTask, _super);
  92110. /**
  92111. * Creates a new ImageAssetTask
  92112. * @param name defines the name of the task
  92113. * @param url defines the location of the image to load
  92114. */
  92115. function ImageAssetTask(
  92116. /**
  92117. * Defines the name of the task
  92118. */
  92119. name,
  92120. /**
  92121. * Defines the location of the image to load
  92122. */
  92123. url) {
  92124. var _this = _super.call(this, name) || this;
  92125. _this.name = name;
  92126. _this.url = url;
  92127. return _this;
  92128. }
  92129. /**
  92130. * Execute the current task
  92131. * @param scene defines the scene where you want your assets to be loaded
  92132. * @param onSuccess is a callback called when the task is successfully executed
  92133. * @param onError is a callback called if an error occurs
  92134. */
  92135. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92136. var _this = this;
  92137. var img = new Image();
  92138. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92139. img.onload = function () {
  92140. _this.image = img;
  92141. onSuccess();
  92142. };
  92143. img.onerror = function (err) {
  92144. onError("Error loading image", err);
  92145. };
  92146. img.src = this.url;
  92147. };
  92148. return ImageAssetTask;
  92149. }(AbstractAssetTask));
  92150. BABYLON.ImageAssetTask = ImageAssetTask;
  92151. /**
  92152. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92153. */
  92154. var TextureAssetTask = /** @class */ (function (_super) {
  92155. __extends(TextureAssetTask, _super);
  92156. /**
  92157. * Creates a new TextureAssetTask object
  92158. * @param name defines the name of the task
  92159. * @param url defines the location of the file to load
  92160. * @param noMipmap defines if mipmap should not be generated (default is false)
  92161. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92162. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92163. */
  92164. function TextureAssetTask(
  92165. /**
  92166. * Defines the name of the task
  92167. */
  92168. name,
  92169. /**
  92170. * Defines the location of the file to load
  92171. */
  92172. url,
  92173. /**
  92174. * Defines if mipmap should not be generated (default is false)
  92175. */
  92176. noMipmap,
  92177. /**
  92178. * Defines if texture must be inverted on Y axis (default is false)
  92179. */
  92180. invertY,
  92181. /**
  92182. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92183. */
  92184. samplingMode) {
  92185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92186. var _this = _super.call(this, name) || this;
  92187. _this.name = name;
  92188. _this.url = url;
  92189. _this.noMipmap = noMipmap;
  92190. _this.invertY = invertY;
  92191. _this.samplingMode = samplingMode;
  92192. return _this;
  92193. }
  92194. /**
  92195. * Execute the current task
  92196. * @param scene defines the scene where you want your assets to be loaded
  92197. * @param onSuccess is a callback called when the task is successfully executed
  92198. * @param onError is a callback called if an error occurs
  92199. */
  92200. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92201. var onload = function () {
  92202. onSuccess();
  92203. };
  92204. var onerror = function (message, exception) {
  92205. onError(message, exception);
  92206. };
  92207. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92208. };
  92209. return TextureAssetTask;
  92210. }(AbstractAssetTask));
  92211. BABYLON.TextureAssetTask = TextureAssetTask;
  92212. /**
  92213. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92214. */
  92215. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92216. __extends(CubeTextureAssetTask, _super);
  92217. /**
  92218. * Creates a new CubeTextureAssetTask
  92219. * @param name defines the name of the task
  92220. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92221. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92222. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92223. * @param files defines the explicit list of files (undefined by default)
  92224. */
  92225. function CubeTextureAssetTask(
  92226. /**
  92227. * Defines the name of the task
  92228. */
  92229. name,
  92230. /**
  92231. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92232. */
  92233. url,
  92234. /**
  92235. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92236. */
  92237. extensions,
  92238. /**
  92239. * Defines if mipmaps should not be generated (default is false)
  92240. */
  92241. noMipmap,
  92242. /**
  92243. * Defines the explicit list of files (undefined by default)
  92244. */
  92245. files) {
  92246. var _this = _super.call(this, name) || this;
  92247. _this.name = name;
  92248. _this.url = url;
  92249. _this.extensions = extensions;
  92250. _this.noMipmap = noMipmap;
  92251. _this.files = files;
  92252. return _this;
  92253. }
  92254. /**
  92255. * Execute the current task
  92256. * @param scene defines the scene where you want your assets to be loaded
  92257. * @param onSuccess is a callback called when the task is successfully executed
  92258. * @param onError is a callback called if an error occurs
  92259. */
  92260. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92261. var onload = function () {
  92262. onSuccess();
  92263. };
  92264. var onerror = function (message, exception) {
  92265. onError(message, exception);
  92266. };
  92267. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92268. };
  92269. return CubeTextureAssetTask;
  92270. }(AbstractAssetTask));
  92271. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92272. /**
  92273. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92274. */
  92275. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92276. __extends(HDRCubeTextureAssetTask, _super);
  92277. /**
  92278. * Creates a new HDRCubeTextureAssetTask object
  92279. * @param name defines the name of the task
  92280. * @param url defines the location of the file to load
  92281. * @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.
  92282. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92283. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92284. * @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)
  92285. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92286. */
  92287. function HDRCubeTextureAssetTask(
  92288. /**
  92289. * Defines the name of the task
  92290. */
  92291. name,
  92292. /**
  92293. * Defines the location of the file to load
  92294. */
  92295. url,
  92296. /**
  92297. * 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.
  92298. */
  92299. size,
  92300. /**
  92301. * Defines if mipmaps should not be generated (default is false)
  92302. */
  92303. noMipmap,
  92304. /**
  92305. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92306. */
  92307. generateHarmonics,
  92308. /**
  92309. * 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)
  92310. */
  92311. useInGammaSpace,
  92312. /**
  92313. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92314. */
  92315. usePMREMGenerator) {
  92316. if (noMipmap === void 0) { noMipmap = false; }
  92317. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92318. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92319. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92320. var _this = _super.call(this, name) || this;
  92321. _this.name = name;
  92322. _this.url = url;
  92323. _this.size = size;
  92324. _this.noMipmap = noMipmap;
  92325. _this.generateHarmonics = generateHarmonics;
  92326. _this.useInGammaSpace = useInGammaSpace;
  92327. _this.usePMREMGenerator = usePMREMGenerator;
  92328. return _this;
  92329. }
  92330. /**
  92331. * Execute the current task
  92332. * @param scene defines the scene where you want your assets to be loaded
  92333. * @param onSuccess is a callback called when the task is successfully executed
  92334. * @param onError is a callback called if an error occurs
  92335. */
  92336. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92337. var onload = function () {
  92338. onSuccess();
  92339. };
  92340. var onerror = function (message, exception) {
  92341. onError(message, exception);
  92342. };
  92343. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  92344. };
  92345. return HDRCubeTextureAssetTask;
  92346. }(AbstractAssetTask));
  92347. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  92348. /**
  92349. * This class can be used to easily import assets into a scene
  92350. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  92351. */
  92352. var AssetsManager = /** @class */ (function () {
  92353. /**
  92354. * Creates a new AssetsManager
  92355. * @param scene defines the scene to work on
  92356. */
  92357. function AssetsManager(scene) {
  92358. this._isLoading = false;
  92359. this._tasks = new Array();
  92360. this._waitingTasksCount = 0;
  92361. this._totalTasksCount = 0;
  92362. /**
  92363. * Observable called when all tasks are processed
  92364. */
  92365. this.onTaskSuccessObservable = new BABYLON.Observable();
  92366. /**
  92367. * Observable called when a task had an error
  92368. */
  92369. this.onTaskErrorObservable = new BABYLON.Observable();
  92370. /**
  92371. * Observable called when a task is successful
  92372. */
  92373. this.onTasksDoneObservable = new BABYLON.Observable();
  92374. /**
  92375. * Observable called when a task is done (whatever the result is)
  92376. */
  92377. this.onProgressObservable = new BABYLON.Observable();
  92378. /**
  92379. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  92380. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  92381. */
  92382. this.useDefaultLoadingScreen = true;
  92383. this._scene = scene;
  92384. }
  92385. /**
  92386. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  92387. * @param taskName defines the name of the new task
  92388. * @param meshesNames defines the name of meshes to load
  92389. * @param rootUrl defines the root url to use to locate files
  92390. * @param sceneFilename defines the filename of the scene file
  92391. * @returns a new {BABYLON.MeshAssetTask} object
  92392. */
  92393. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  92394. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  92395. this._tasks.push(task);
  92396. return task;
  92397. };
  92398. /**
  92399. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  92400. * @param taskName defines the name of the new task
  92401. * @param url defines the url of the file to load
  92402. * @returns a new {BABYLON.TextFileAssetTask} object
  92403. */
  92404. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  92405. var task = new TextFileAssetTask(taskName, url);
  92406. this._tasks.push(task);
  92407. return task;
  92408. };
  92409. /**
  92410. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  92411. * @param taskName defines the name of the new task
  92412. * @param url defines the url of the file to load
  92413. * @returns a new {BABYLON.BinaryFileAssetTask} object
  92414. */
  92415. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  92416. var task = new BinaryFileAssetTask(taskName, url);
  92417. this._tasks.push(task);
  92418. return task;
  92419. };
  92420. /**
  92421. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  92422. * @param taskName defines the name of the new task
  92423. * @param url defines the url of the file to load
  92424. * @returns a new {BABYLON.ImageAssetTask} object
  92425. */
  92426. AssetsManager.prototype.addImageTask = function (taskName, url) {
  92427. var task = new ImageAssetTask(taskName, url);
  92428. this._tasks.push(task);
  92429. return task;
  92430. };
  92431. /**
  92432. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  92433. * @param taskName defines the name of the new task
  92434. * @param url defines the url of the file to load
  92435. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92436. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  92437. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  92438. * @returns a new {BABYLON.TextureAssetTask} object
  92439. */
  92440. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  92441. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92442. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  92443. this._tasks.push(task);
  92444. return task;
  92445. };
  92446. /**
  92447. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  92448. * @param taskName defines the name of the new task
  92449. * @param url defines the url of the file to load
  92450. * @param extensions defines the extension to use to load the cube map (can be null)
  92451. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92452. * @param files defines the list of files to load (can be null)
  92453. * @returns a new {BABYLON.CubeTextureAssetTask} object
  92454. */
  92455. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  92456. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  92457. this._tasks.push(task);
  92458. return task;
  92459. };
  92460. /**
  92461. *
  92462. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  92463. * @param taskName defines the name of the new task
  92464. * @param url defines the url of the file to load
  92465. * @param size defines the size you want for the cubemap (can be null)
  92466. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92467. * @param generateHarmonics defines if you want to automatically generate (true by default)
  92468. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  92469. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  92470. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  92471. */
  92472. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  92473. if (noMipmap === void 0) { noMipmap = false; }
  92474. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92475. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92476. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92477. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  92478. this._tasks.push(task);
  92479. return task;
  92480. };
  92481. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  92482. var _this = this;
  92483. this._waitingTasksCount--;
  92484. try {
  92485. if (task.taskState === AssetTaskState.DONE) {
  92486. // Let's remove successfull tasks
  92487. BABYLON.Tools.SetImmediate(function () {
  92488. var index = _this._tasks.indexOf(task);
  92489. if (index > -1) {
  92490. _this._tasks.splice(index, 1);
  92491. }
  92492. });
  92493. }
  92494. if (this.onProgress) {
  92495. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  92496. }
  92497. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  92498. }
  92499. catch (e) {
  92500. BABYLON.Tools.Error("Error running progress callbacks.");
  92501. console.log(e);
  92502. }
  92503. if (this._waitingTasksCount === 0) {
  92504. try {
  92505. if (this.onFinish) {
  92506. this.onFinish(this._tasks);
  92507. }
  92508. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92509. }
  92510. catch (e) {
  92511. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  92512. console.log(e);
  92513. }
  92514. this._isLoading = false;
  92515. this._scene.getEngine().hideLoadingUI();
  92516. }
  92517. };
  92518. AssetsManager.prototype._runTask = function (task) {
  92519. var _this = this;
  92520. var done = function () {
  92521. try {
  92522. if (_this.onTaskSuccess) {
  92523. _this.onTaskSuccess(task);
  92524. }
  92525. _this.onTaskSuccessObservable.notifyObservers(task);
  92526. _this._decreaseWaitingTasksCount(task);
  92527. }
  92528. catch (e) {
  92529. error("Error executing task success callbacks", e);
  92530. }
  92531. };
  92532. var error = function (message, exception) {
  92533. task._setErrorObject(message, exception);
  92534. if (_this.onTaskError) {
  92535. _this.onTaskError(task);
  92536. }
  92537. _this.onTaskErrorObservable.notifyObservers(task);
  92538. _this._decreaseWaitingTasksCount(task);
  92539. };
  92540. task.run(this._scene, done, error);
  92541. };
  92542. /**
  92543. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92544. * @return the current instance of the {BABYLON.AssetsManager}
  92545. */
  92546. AssetsManager.prototype.reset = function () {
  92547. this._isLoading = false;
  92548. this._tasks = new Array();
  92549. return this;
  92550. };
  92551. /**
  92552. * Start the loading process
  92553. * @return the current instance of the {BABYLON.AssetsManager}
  92554. */
  92555. AssetsManager.prototype.load = function () {
  92556. if (this._isLoading) {
  92557. return this;
  92558. }
  92559. this._isLoading = true;
  92560. this._waitingTasksCount = this._tasks.length;
  92561. this._totalTasksCount = this._tasks.length;
  92562. if (this._waitingTasksCount === 0) {
  92563. this._isLoading = false;
  92564. if (this.onFinish) {
  92565. this.onFinish(this._tasks);
  92566. }
  92567. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92568. return this;
  92569. }
  92570. if (this.useDefaultLoadingScreen) {
  92571. this._scene.getEngine().displayLoadingUI();
  92572. }
  92573. for (var index = 0; index < this._tasks.length; index++) {
  92574. var task = this._tasks[index];
  92575. this._runTask(task);
  92576. }
  92577. return this;
  92578. };
  92579. return AssetsManager;
  92580. }());
  92581. BABYLON.AssetsManager = AssetsManager;
  92582. })(BABYLON || (BABYLON = {}));
  92583. //# sourceMappingURL=babylon.assetsManager.js.map
  92584. var BABYLON;
  92585. (function (BABYLON) {
  92586. var serializedGeometries = [];
  92587. var serializeGeometry = function (geometry, serializationGeometries) {
  92588. if (serializedGeometries[geometry.id]) {
  92589. return;
  92590. }
  92591. if (geometry.doNotSerialize) {
  92592. return;
  92593. }
  92594. if (geometry instanceof BABYLON.BoxGeometry) {
  92595. serializationGeometries.boxes.push(geometry.serialize());
  92596. }
  92597. else if (geometry instanceof BABYLON.SphereGeometry) {
  92598. serializationGeometries.spheres.push(geometry.serialize());
  92599. }
  92600. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92601. serializationGeometries.cylinders.push(geometry.serialize());
  92602. }
  92603. else if (geometry instanceof BABYLON.TorusGeometry) {
  92604. serializationGeometries.toruses.push(geometry.serialize());
  92605. }
  92606. else if (geometry instanceof BABYLON.GroundGeometry) {
  92607. serializationGeometries.grounds.push(geometry.serialize());
  92608. }
  92609. else if (geometry instanceof BABYLON.Plane) {
  92610. serializationGeometries.planes.push(geometry.serialize());
  92611. }
  92612. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92613. serializationGeometries.torusKnots.push(geometry.serialize());
  92614. }
  92615. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92616. throw new Error("Unknown primitive type");
  92617. }
  92618. else {
  92619. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92620. }
  92621. serializedGeometries[geometry.id] = true;
  92622. };
  92623. var serializeMesh = function (mesh, serializationScene) {
  92624. var serializationObject = {};
  92625. // Geometry
  92626. var geometry = mesh._geometry;
  92627. if (geometry) {
  92628. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92629. // 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
  92630. serializeGeometry(geometry, serializationScene.geometries);
  92631. }
  92632. }
  92633. // Custom
  92634. if (mesh.serialize) {
  92635. mesh.serialize(serializationObject);
  92636. }
  92637. return serializationObject;
  92638. };
  92639. var finalizeSingleMesh = function (mesh, serializationObject) {
  92640. //only works if the mesh is already loaded
  92641. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92642. //serialize material
  92643. if (mesh.material) {
  92644. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92645. serializationObject.materials = serializationObject.materials || [];
  92646. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92647. serializationObject.materials.push(mesh.material.serialize());
  92648. }
  92649. }
  92650. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92651. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92652. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92653. serializationObject.multiMaterials.push(mesh.material.serialize());
  92654. }
  92655. }
  92656. }
  92657. //serialize geometry
  92658. var geometry = mesh._geometry;
  92659. if (geometry) {
  92660. if (!serializationObject.geometries) {
  92661. serializationObject.geometries = {};
  92662. serializationObject.geometries.boxes = [];
  92663. serializationObject.geometries.spheres = [];
  92664. serializationObject.geometries.cylinders = [];
  92665. serializationObject.geometries.toruses = [];
  92666. serializationObject.geometries.grounds = [];
  92667. serializationObject.geometries.planes = [];
  92668. serializationObject.geometries.torusKnots = [];
  92669. serializationObject.geometries.vertexData = [];
  92670. }
  92671. serializeGeometry(geometry, serializationObject.geometries);
  92672. }
  92673. // Skeletons
  92674. if (mesh.skeleton) {
  92675. serializationObject.skeletons = serializationObject.skeletons || [];
  92676. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92677. }
  92678. //serialize the actual mesh
  92679. serializationObject.meshes = serializationObject.meshes || [];
  92680. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92681. }
  92682. };
  92683. var SceneSerializer = /** @class */ (function () {
  92684. function SceneSerializer() {
  92685. }
  92686. SceneSerializer.ClearCache = function () {
  92687. serializedGeometries = [];
  92688. };
  92689. SceneSerializer.Serialize = function (scene) {
  92690. var serializationObject = {};
  92691. SceneSerializer.ClearCache();
  92692. // Scene
  92693. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92694. serializationObject.autoClear = scene.autoClear;
  92695. serializationObject.clearColor = scene.clearColor.asArray();
  92696. serializationObject.ambientColor = scene.ambientColor.asArray();
  92697. serializationObject.gravity = scene.gravity.asArray();
  92698. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92699. serializationObject.workerCollisions = scene.workerCollisions;
  92700. // Fog
  92701. if (scene.fogMode && scene.fogMode !== 0) {
  92702. serializationObject.fogMode = scene.fogMode;
  92703. serializationObject.fogColor = scene.fogColor.asArray();
  92704. serializationObject.fogStart = scene.fogStart;
  92705. serializationObject.fogEnd = scene.fogEnd;
  92706. serializationObject.fogDensity = scene.fogDensity;
  92707. }
  92708. //Physics
  92709. if (scene.isPhysicsEnabled()) {
  92710. var physicEngine = scene.getPhysicsEngine();
  92711. if (physicEngine) {
  92712. serializationObject.physicsEnabled = true;
  92713. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92714. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92715. }
  92716. }
  92717. // Metadata
  92718. if (scene.metadata) {
  92719. serializationObject.metadata = scene.metadata;
  92720. }
  92721. // Morph targets
  92722. serializationObject.morphTargetManagers = [];
  92723. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92724. var abstractMesh = _a[_i];
  92725. var manager = abstractMesh.morphTargetManager;
  92726. if (manager) {
  92727. serializationObject.morphTargetManagers.push(manager.serialize());
  92728. }
  92729. }
  92730. // Lights
  92731. serializationObject.lights = [];
  92732. var index;
  92733. var light;
  92734. for (index = 0; index < scene.lights.length; index++) {
  92735. light = scene.lights[index];
  92736. if (!light.doNotSerialize) {
  92737. serializationObject.lights.push(light.serialize());
  92738. }
  92739. }
  92740. // Cameras
  92741. serializationObject.cameras = [];
  92742. for (index = 0; index < scene.cameras.length; index++) {
  92743. var camera = scene.cameras[index];
  92744. if (!camera.doNotSerialize) {
  92745. serializationObject.cameras.push(camera.serialize());
  92746. }
  92747. }
  92748. if (scene.activeCamera) {
  92749. serializationObject.activeCameraID = scene.activeCamera.id;
  92750. }
  92751. // Animations
  92752. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92753. // Materials
  92754. serializationObject.materials = [];
  92755. serializationObject.multiMaterials = [];
  92756. var material;
  92757. for (index = 0; index < scene.materials.length; index++) {
  92758. material = scene.materials[index];
  92759. if (!material.doNotSerialize) {
  92760. serializationObject.materials.push(material.serialize());
  92761. }
  92762. }
  92763. // MultiMaterials
  92764. serializationObject.multiMaterials = [];
  92765. for (index = 0; index < scene.multiMaterials.length; index++) {
  92766. var multiMaterial = scene.multiMaterials[index];
  92767. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92768. }
  92769. // Environment texture
  92770. if (scene.environmentTexture) {
  92771. serializationObject.environmentTexture = scene.environmentTexture.name;
  92772. }
  92773. // Skeletons
  92774. serializationObject.skeletons = [];
  92775. for (index = 0; index < scene.skeletons.length; index++) {
  92776. var skeleton = scene.skeletons[index];
  92777. if (!skeleton.doNotSerialize) {
  92778. serializationObject.skeletons.push(skeleton.serialize());
  92779. }
  92780. }
  92781. // Transform nodes
  92782. serializationObject.transformNodes = [];
  92783. for (index = 0; index < scene.transformNodes.length; index++) {
  92784. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92785. }
  92786. // Geometries
  92787. serializationObject.geometries = {};
  92788. serializationObject.geometries.boxes = [];
  92789. serializationObject.geometries.spheres = [];
  92790. serializationObject.geometries.cylinders = [];
  92791. serializationObject.geometries.toruses = [];
  92792. serializationObject.geometries.grounds = [];
  92793. serializationObject.geometries.planes = [];
  92794. serializationObject.geometries.torusKnots = [];
  92795. serializationObject.geometries.vertexData = [];
  92796. serializedGeometries = [];
  92797. var geometries = scene.getGeometries();
  92798. for (index = 0; index < geometries.length; index++) {
  92799. var geometry = geometries[index];
  92800. if (geometry.isReady()) {
  92801. serializeGeometry(geometry, serializationObject.geometries);
  92802. }
  92803. }
  92804. // Meshes
  92805. serializationObject.meshes = [];
  92806. for (index = 0; index < scene.meshes.length; index++) {
  92807. var abstractMesh = scene.meshes[index];
  92808. if (abstractMesh instanceof BABYLON.Mesh) {
  92809. var mesh = abstractMesh;
  92810. if (!mesh.doNotSerialize) {
  92811. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92812. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92813. }
  92814. }
  92815. }
  92816. }
  92817. // Particles Systems
  92818. serializationObject.particleSystems = [];
  92819. for (index = 0; index < scene.particleSystems.length; index++) {
  92820. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  92821. }
  92822. // Lens flares
  92823. serializationObject.lensFlareSystems = [];
  92824. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  92825. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  92826. }
  92827. // Shadows
  92828. serializationObject.shadowGenerators = [];
  92829. for (index = 0; index < scene.lights.length; index++) {
  92830. light = scene.lights[index];
  92831. var shadowGenerator = light.getShadowGenerator();
  92832. if (shadowGenerator) {
  92833. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  92834. }
  92835. }
  92836. // Action Manager
  92837. if (scene.actionManager) {
  92838. serializationObject.actions = scene.actionManager.serialize("scene");
  92839. }
  92840. // Audio
  92841. serializationObject.sounds = [];
  92842. for (index = 0; index < scene.soundTracks.length; index++) {
  92843. var soundtrack = scene.soundTracks[index];
  92844. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  92845. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  92846. }
  92847. }
  92848. // Effect layers
  92849. serializationObject.effectLayers = [];
  92850. for (index = 0; index < scene.effectLayers.length; index++) {
  92851. var layer = scene.effectLayers[index];
  92852. if (layer.serialize) {
  92853. serializationObject.effectLayers.push(layer.serialize());
  92854. }
  92855. }
  92856. return serializationObject;
  92857. };
  92858. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  92859. if (withParents === void 0) { withParents = false; }
  92860. if (withChildren === void 0) { withChildren = false; }
  92861. var serializationObject = {};
  92862. SceneSerializer.ClearCache();
  92863. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  92864. if (withParents || withChildren) {
  92865. //deliberate for loop! not for each, appended should be processed as well.
  92866. for (var i = 0; i < toSerialize.length; ++i) {
  92867. if (withChildren) {
  92868. toSerialize[i].getDescendants().forEach(function (node) {
  92869. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  92870. toSerialize.push(node);
  92871. }
  92872. });
  92873. }
  92874. //make sure the array doesn't contain the object already
  92875. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  92876. toSerialize.push(toSerialize[i].parent);
  92877. }
  92878. }
  92879. }
  92880. toSerialize.forEach(function (mesh) {
  92881. finalizeSingleMesh(mesh, serializationObject);
  92882. });
  92883. return serializationObject;
  92884. };
  92885. return SceneSerializer;
  92886. }());
  92887. BABYLON.SceneSerializer = SceneSerializer;
  92888. })(BABYLON || (BABYLON = {}));
  92889. //# sourceMappingURL=babylon.sceneSerializer.js.map
  92890. var BABYLON;
  92891. (function (BABYLON) {
  92892. var ReflectionProbe = /** @class */ (function () {
  92893. function ReflectionProbe(name, size, scene, generateMipMaps) {
  92894. if (generateMipMaps === void 0) { generateMipMaps = true; }
  92895. var _this = this;
  92896. this.name = name;
  92897. this._viewMatrix = BABYLON.Matrix.Identity();
  92898. this._target = BABYLON.Vector3.Zero();
  92899. this._add = BABYLON.Vector3.Zero();
  92900. this._invertYAxis = false;
  92901. this.position = BABYLON.Vector3.Zero();
  92902. this._scene = scene;
  92903. this._scene.reflectionProbes.push(this);
  92904. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  92905. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  92906. switch (faceIndex) {
  92907. case 0:
  92908. _this._add.copyFromFloats(1, 0, 0);
  92909. break;
  92910. case 1:
  92911. _this._add.copyFromFloats(-1, 0, 0);
  92912. break;
  92913. case 2:
  92914. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  92915. break;
  92916. case 3:
  92917. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  92918. break;
  92919. case 4:
  92920. _this._add.copyFromFloats(0, 0, 1);
  92921. break;
  92922. case 5:
  92923. _this._add.copyFromFloats(0, 0, -1);
  92924. break;
  92925. }
  92926. if (_this._attachedMesh) {
  92927. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  92928. }
  92929. _this.position.addToRef(_this._add, _this._target);
  92930. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  92931. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  92932. scene._forcedViewPosition = _this.position;
  92933. });
  92934. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  92935. scene._forcedViewPosition = null;
  92936. scene.updateTransformMatrix(true);
  92937. });
  92938. if (scene.activeCamera) {
  92939. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  92940. }
  92941. }
  92942. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  92943. get: function () {
  92944. return this._renderTargetTexture.samples;
  92945. },
  92946. set: function (value) {
  92947. this._renderTargetTexture.samples = value;
  92948. },
  92949. enumerable: true,
  92950. configurable: true
  92951. });
  92952. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  92953. get: function () {
  92954. return this._renderTargetTexture.refreshRate;
  92955. },
  92956. set: function (value) {
  92957. this._renderTargetTexture.refreshRate = value;
  92958. },
  92959. enumerable: true,
  92960. configurable: true
  92961. });
  92962. ReflectionProbe.prototype.getScene = function () {
  92963. return this._scene;
  92964. };
  92965. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  92966. get: function () {
  92967. return this._renderTargetTexture;
  92968. },
  92969. enumerable: true,
  92970. configurable: true
  92971. });
  92972. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  92973. get: function () {
  92974. return this._renderTargetTexture.renderList;
  92975. },
  92976. enumerable: true,
  92977. configurable: true
  92978. });
  92979. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  92980. this._attachedMesh = mesh;
  92981. };
  92982. /**
  92983. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  92984. *
  92985. * @param renderingGroupId The rendering group id corresponding to its index
  92986. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  92987. */
  92988. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  92989. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  92990. };
  92991. ReflectionProbe.prototype.dispose = function () {
  92992. var index = this._scene.reflectionProbes.indexOf(this);
  92993. if (index !== -1) {
  92994. // Remove from the scene if found
  92995. this._scene.reflectionProbes.splice(index, 1);
  92996. }
  92997. if (this._renderTargetTexture) {
  92998. this._renderTargetTexture.dispose();
  92999. this._renderTargetTexture = null;
  93000. }
  93001. };
  93002. return ReflectionProbe;
  93003. }());
  93004. BABYLON.ReflectionProbe = ReflectionProbe;
  93005. })(BABYLON || (BABYLON = {}));
  93006. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93007. var BABYLON;
  93008. (function (BABYLON) {
  93009. var Layer = /** @class */ (function () {
  93010. function Layer(name, imgUrl, scene, isBackground, color) {
  93011. this.name = name;
  93012. this.scale = new BABYLON.Vector2(1, 1);
  93013. this.offset = new BABYLON.Vector2(0, 0);
  93014. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93015. this.layerMask = 0x0FFFFFFF;
  93016. this._vertexBuffers = {};
  93017. // Events
  93018. /**
  93019. * An event triggered when the layer is disposed.
  93020. */
  93021. this.onDisposeObservable = new BABYLON.Observable();
  93022. /**
  93023. * An event triggered before rendering the scene
  93024. */
  93025. this.onBeforeRenderObservable = new BABYLON.Observable();
  93026. /**
  93027. * An event triggered after rendering the scene
  93028. */
  93029. this.onAfterRenderObservable = new BABYLON.Observable();
  93030. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93031. this.isBackground = isBackground === undefined ? true : isBackground;
  93032. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93033. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93034. this._scene.layers.push(this);
  93035. var engine = this._scene.getEngine();
  93036. // VBO
  93037. var vertices = [];
  93038. vertices.push(1, 1);
  93039. vertices.push(-1, 1);
  93040. vertices.push(-1, -1);
  93041. vertices.push(1, -1);
  93042. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93043. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93044. this._createIndexBuffer();
  93045. // Effects
  93046. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93047. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93048. }
  93049. Object.defineProperty(Layer.prototype, "onDispose", {
  93050. set: function (callback) {
  93051. if (this._onDisposeObserver) {
  93052. this.onDisposeObservable.remove(this._onDisposeObserver);
  93053. }
  93054. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93055. },
  93056. enumerable: true,
  93057. configurable: true
  93058. });
  93059. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93060. set: function (callback) {
  93061. if (this._onBeforeRenderObserver) {
  93062. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93063. }
  93064. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93065. },
  93066. enumerable: true,
  93067. configurable: true
  93068. });
  93069. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93070. set: function (callback) {
  93071. if (this._onAfterRenderObserver) {
  93072. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93073. }
  93074. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93075. },
  93076. enumerable: true,
  93077. configurable: true
  93078. });
  93079. Layer.prototype._createIndexBuffer = function () {
  93080. var engine = this._scene.getEngine();
  93081. // Indices
  93082. var indices = [];
  93083. indices.push(0);
  93084. indices.push(1);
  93085. indices.push(2);
  93086. indices.push(0);
  93087. indices.push(2);
  93088. indices.push(3);
  93089. this._indexBuffer = engine.createIndexBuffer(indices);
  93090. };
  93091. Layer.prototype._rebuild = function () {
  93092. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93093. if (vb) {
  93094. vb._rebuild();
  93095. }
  93096. this._createIndexBuffer();
  93097. };
  93098. Layer.prototype.render = function () {
  93099. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93100. // Check
  93101. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93102. return;
  93103. var engine = this._scene.getEngine();
  93104. this.onBeforeRenderObservable.notifyObservers(this);
  93105. // Render
  93106. engine.enableEffect(currentEffect);
  93107. engine.setState(false);
  93108. // Texture
  93109. currentEffect.setTexture("textureSampler", this.texture);
  93110. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93111. // Color
  93112. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93113. // Scale / offset
  93114. currentEffect.setVector2("offset", this.offset);
  93115. currentEffect.setVector2("scale", this.scale);
  93116. // VBOs
  93117. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93118. // Draw order
  93119. if (!this.alphaTest) {
  93120. engine.setAlphaMode(this.alphaBlendingMode);
  93121. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93122. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93123. }
  93124. else {
  93125. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93126. }
  93127. this.onAfterRenderObservable.notifyObservers(this);
  93128. };
  93129. Layer.prototype.dispose = function () {
  93130. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93131. if (vertexBuffer) {
  93132. vertexBuffer.dispose();
  93133. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93134. }
  93135. if (this._indexBuffer) {
  93136. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93137. this._indexBuffer = null;
  93138. }
  93139. if (this.texture) {
  93140. this.texture.dispose();
  93141. this.texture = null;
  93142. }
  93143. // Remove from scene
  93144. var index = this._scene.layers.indexOf(this);
  93145. this._scene.layers.splice(index, 1);
  93146. // Callback
  93147. this.onDisposeObservable.notifyObservers(this);
  93148. this.onDisposeObservable.clear();
  93149. this.onAfterRenderObservable.clear();
  93150. this.onBeforeRenderObservable.clear();
  93151. };
  93152. return Layer;
  93153. }());
  93154. BABYLON.Layer = Layer;
  93155. })(BABYLON || (BABYLON = {}));
  93156. //# sourceMappingURL=babylon.layer.js.map
  93157. var BABYLON;
  93158. (function (BABYLON) {
  93159. var TextureTools = /** @class */ (function () {
  93160. function TextureTools() {
  93161. }
  93162. /**
  93163. * Uses the GPU to create a copy texture rescaled at a given size
  93164. * @param texture Texture to copy from
  93165. * @param width Desired width
  93166. * @param height Desired height
  93167. * @return Generated texture
  93168. */
  93169. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93170. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93171. var scene = texture.getScene();
  93172. var engine = scene.getEngine();
  93173. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93174. rtt.wrapU = texture.wrapU;
  93175. rtt.wrapV = texture.wrapV;
  93176. rtt.uOffset = texture.uOffset;
  93177. rtt.vOffset = texture.vOffset;
  93178. rtt.uScale = texture.uScale;
  93179. rtt.vScale = texture.vScale;
  93180. rtt.uAng = texture.uAng;
  93181. rtt.vAng = texture.vAng;
  93182. rtt.wAng = texture.wAng;
  93183. rtt.coordinatesIndex = texture.coordinatesIndex;
  93184. rtt.level = texture.level;
  93185. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93186. rtt._texture.isReady = false;
  93187. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93188. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93189. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93190. passPostProcess.getEffect().executeWhenCompiled(function () {
  93191. passPostProcess.onApply = function (effect) {
  93192. effect.setTexture("textureSampler", texture);
  93193. };
  93194. var internalTexture = rtt.getInternalTexture();
  93195. if (internalTexture) {
  93196. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93197. engine.unBindFramebuffer(internalTexture);
  93198. rtt.disposeFramebufferObjects();
  93199. passPostProcess.dispose();
  93200. internalTexture.isReady = true;
  93201. }
  93202. });
  93203. return rtt;
  93204. };
  93205. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93206. if (!scene._environmentBRDFTexture) {
  93207. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93208. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93209. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93210. scene._environmentBRDFTexture = texture;
  93211. }
  93212. return scene._environmentBRDFTexture;
  93213. };
  93214. 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=";
  93215. return TextureTools;
  93216. }());
  93217. BABYLON.TextureTools = TextureTools;
  93218. })(BABYLON || (BABYLON = {}));
  93219. //# sourceMappingURL=babylon.textureTools.js.map
  93220. var BABYLON;
  93221. (function (BABYLON) {
  93222. var FramingBehavior = /** @class */ (function () {
  93223. function FramingBehavior() {
  93224. this._mode = FramingBehavior.FitFrustumSidesMode;
  93225. this._radiusScale = 1.0;
  93226. this._positionScale = 0.5;
  93227. this._defaultElevation = 0.3;
  93228. this._elevationReturnTime = 1500;
  93229. this._elevationReturnWaitTime = 1000;
  93230. this._zoomStopsAnimation = false;
  93231. this._framingTime = 1500;
  93232. this._isPointerDown = false;
  93233. this._lastInteractionTime = -Infinity;
  93234. // Framing control
  93235. this._animatables = new Array();
  93236. this._betaIsAnimating = false;
  93237. }
  93238. Object.defineProperty(FramingBehavior.prototype, "name", {
  93239. get: function () {
  93240. return "Framing";
  93241. },
  93242. enumerable: true,
  93243. configurable: true
  93244. });
  93245. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93246. /**
  93247. * Gets current mode used by the behavior.
  93248. */
  93249. get: function () {
  93250. return this._mode;
  93251. },
  93252. /**
  93253. * Sets the current mode used by the behavior
  93254. */
  93255. set: function (mode) {
  93256. this._mode = mode;
  93257. },
  93258. enumerable: true,
  93259. configurable: true
  93260. });
  93261. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93262. /**
  93263. * Gets the scale applied to the radius
  93264. */
  93265. get: function () {
  93266. return this._radiusScale;
  93267. },
  93268. /**
  93269. * Sets the scale applied to the radius (1 by default)
  93270. */
  93271. set: function (radius) {
  93272. this._radiusScale = radius;
  93273. },
  93274. enumerable: true,
  93275. configurable: true
  93276. });
  93277. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93278. /**
  93279. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93280. */
  93281. get: function () {
  93282. return this._positionScale;
  93283. },
  93284. /**
  93285. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93286. */
  93287. set: function (scale) {
  93288. this._positionScale = scale;
  93289. },
  93290. enumerable: true,
  93291. configurable: true
  93292. });
  93293. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93294. /**
  93295. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93296. * behaviour is triggered, in radians.
  93297. */
  93298. get: function () {
  93299. return this._defaultElevation;
  93300. },
  93301. /**
  93302. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93303. * behaviour is triggered, in radians.
  93304. */
  93305. set: function (elevation) {
  93306. this._defaultElevation = elevation;
  93307. },
  93308. enumerable: true,
  93309. configurable: true
  93310. });
  93311. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93312. /**
  93313. * Gets the time (in milliseconds) taken to return to the default beta position.
  93314. * Negative value indicates camera should not return to default.
  93315. */
  93316. get: function () {
  93317. return this._elevationReturnTime;
  93318. },
  93319. /**
  93320. * Sets the time (in milliseconds) taken to return to the default beta position.
  93321. * Negative value indicates camera should not return to default.
  93322. */
  93323. set: function (speed) {
  93324. this._elevationReturnTime = speed;
  93325. },
  93326. enumerable: true,
  93327. configurable: true
  93328. });
  93329. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  93330. /**
  93331. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93332. */
  93333. get: function () {
  93334. return this._elevationReturnWaitTime;
  93335. },
  93336. /**
  93337. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93338. */
  93339. set: function (time) {
  93340. this._elevationReturnWaitTime = time;
  93341. },
  93342. enumerable: true,
  93343. configurable: true
  93344. });
  93345. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  93346. /**
  93347. * Gets the flag that indicates if user zooming should stop animation.
  93348. */
  93349. get: function () {
  93350. return this._zoomStopsAnimation;
  93351. },
  93352. /**
  93353. * Sets the flag that indicates if user zooming should stop animation.
  93354. */
  93355. set: function (flag) {
  93356. this._zoomStopsAnimation = flag;
  93357. },
  93358. enumerable: true,
  93359. configurable: true
  93360. });
  93361. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  93362. /**
  93363. * Gets the transition time when framing the mesh, in milliseconds
  93364. */
  93365. get: function () {
  93366. return this._framingTime;
  93367. },
  93368. /**
  93369. * Sets the transition time when framing the mesh, in milliseconds
  93370. */
  93371. set: function (time) {
  93372. this._framingTime = time;
  93373. },
  93374. enumerable: true,
  93375. configurable: true
  93376. });
  93377. FramingBehavior.prototype.init = function () {
  93378. // Do notihng
  93379. };
  93380. FramingBehavior.prototype.attach = function (camera) {
  93381. var _this = this;
  93382. this._attachedCamera = camera;
  93383. var scene = this._attachedCamera.getScene();
  93384. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  93385. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93386. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93387. _this._isPointerDown = true;
  93388. return;
  93389. }
  93390. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93391. _this._isPointerDown = false;
  93392. }
  93393. });
  93394. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93395. if (mesh) {
  93396. _this.zoomOnMesh(mesh);
  93397. }
  93398. });
  93399. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93400. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93401. _this._applyUserInteraction();
  93402. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  93403. // back to the default position after a given timeout
  93404. _this._maintainCameraAboveGround();
  93405. });
  93406. };
  93407. FramingBehavior.prototype.detach = function () {
  93408. if (!this._attachedCamera) {
  93409. return;
  93410. }
  93411. var scene = this._attachedCamera.getScene();
  93412. if (this._onPrePointerObservableObserver) {
  93413. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93414. }
  93415. if (this._onAfterCheckInputsObserver) {
  93416. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93417. }
  93418. if (this._onMeshTargetChangedObserver) {
  93419. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93420. }
  93421. this._attachedCamera = null;
  93422. };
  93423. /**
  93424. * Targets the given mesh and updates zoom level accordingly.
  93425. * @param mesh The mesh to target.
  93426. * @param radius Optional. If a cached radius position already exists, overrides default.
  93427. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93428. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93429. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93430. */
  93431. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93432. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93433. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93434. mesh.computeWorldMatrix(true);
  93435. var boundingBox = mesh.getBoundingInfo().boundingBox;
  93436. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  93437. };
  93438. /**
  93439. * Targets the given mesh with its children and updates zoom level accordingly.
  93440. * @param mesh The mesh to target.
  93441. * @param radius Optional. If a cached radius position already exists, overrides default.
  93442. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93443. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93444. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93445. */
  93446. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93447. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93448. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93449. mesh.computeWorldMatrix(true);
  93450. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  93451. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  93452. };
  93453. /**
  93454. * Targets the given meshes with their children and updates zoom level accordingly.
  93455. * @param meshes The mesh to target.
  93456. * @param radius Optional. If a cached radius position already exists, overrides default.
  93457. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93458. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93459. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93460. */
  93461. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  93462. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93463. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93464. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  93465. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  93466. for (var i = 0; i < meshes.length; i++) {
  93467. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  93468. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  93469. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  93470. }
  93471. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  93472. };
  93473. /**
  93474. * Targets the given mesh and updates zoom level accordingly.
  93475. * @param mesh The mesh to target.
  93476. * @param radius Optional. If a cached radius position already exists, overrides default.
  93477. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93478. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93479. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93480. */
  93481. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  93482. var _this = this;
  93483. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93484. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93485. var zoomTarget;
  93486. if (!this._attachedCamera) {
  93487. return;
  93488. }
  93489. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  93490. var bottom = minimumWorld.y;
  93491. var top = maximumWorld.y;
  93492. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  93493. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  93494. if (focusOnOriginXZ) {
  93495. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  93496. }
  93497. else {
  93498. var centerWorld = minimumWorld.add(radiusWorld);
  93499. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  93500. }
  93501. if (!this._vectorTransition) {
  93502. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  93503. }
  93504. this._betaIsAnimating = true;
  93505. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  93506. if (animatable) {
  93507. this._animatables.push(animatable);
  93508. }
  93509. // sets the radius and lower radius bounds
  93510. // Small delta ensures camera is not always at lower zoom limit.
  93511. var radius = 0;
  93512. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  93513. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93514. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  93515. radius = position;
  93516. }
  93517. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93518. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93519. if (this._attachedCamera.lowerRadiusLimit === null) {
  93520. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  93521. }
  93522. }
  93523. // Set sensibilities
  93524. var extend = maximumWorld.subtract(minimumWorld).length();
  93525. this._attachedCamera.panningSensibility = 5000 / extend;
  93526. this._attachedCamera.wheelPrecision = 100 / radius;
  93527. // transition to new radius
  93528. if (!this._radiusTransition) {
  93529. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93530. }
  93531. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  93532. _this.stopAllAnimations();
  93533. if (onAnimationEnd) {
  93534. onAnimationEnd();
  93535. }
  93536. if (_this._attachedCamera) {
  93537. _this._attachedCamera.storeState();
  93538. }
  93539. });
  93540. if (animatable) {
  93541. this._animatables.push(animatable);
  93542. }
  93543. };
  93544. /**
  93545. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93546. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93547. * frustum width.
  93548. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93549. * to fully enclose the mesh in the viewing frustum.
  93550. */
  93551. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93552. var size = maximumWorld.subtract(minimumWorld);
  93553. var boxVectorGlobalDiagonal = size.length();
  93554. var frustumSlope = this._getFrustumSlope();
  93555. // Formula for setting distance
  93556. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93557. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93558. // Horizon distance
  93559. var radius = radiusWithoutFraming * this._radiusScale;
  93560. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93561. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93562. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93563. var camera = this._attachedCamera;
  93564. if (!camera) {
  93565. return 0;
  93566. }
  93567. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93568. // Don't exceed the requested limit
  93569. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93570. }
  93571. // Don't exceed the upper radius limit
  93572. if (camera.upperRadiusLimit) {
  93573. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93574. }
  93575. return distance;
  93576. };
  93577. /**
  93578. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93579. * is automatically returned to its default position (expected to be above ground plane).
  93580. */
  93581. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93582. var _this = this;
  93583. if (this._elevationReturnTime < 0) {
  93584. return;
  93585. }
  93586. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93587. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93588. var limitBeta = Math.PI * 0.5;
  93589. // Bring the camera back up if below the ground plane
  93590. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93591. this._betaIsAnimating = true;
  93592. //Transition to new position
  93593. this.stopAllAnimations();
  93594. if (!this._betaTransition) {
  93595. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93596. }
  93597. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93598. _this._clearAnimationLocks();
  93599. _this.stopAllAnimations();
  93600. });
  93601. if (animatabe) {
  93602. this._animatables.push(animatabe);
  93603. }
  93604. }
  93605. };
  93606. /**
  93607. * Returns the frustum slope based on the canvas ratio and camera FOV
  93608. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93609. */
  93610. FramingBehavior.prototype._getFrustumSlope = function () {
  93611. // Calculate the viewport ratio
  93612. // Aspect Ratio is Height/Width.
  93613. var camera = this._attachedCamera;
  93614. if (!camera) {
  93615. return BABYLON.Vector2.Zero();
  93616. }
  93617. var engine = camera.getScene().getEngine();
  93618. var aspectRatio = engine.getAspectRatio(camera);
  93619. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93620. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93621. var frustumSlopeY = Math.tan(camera.fov / 2);
  93622. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93623. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93624. // along the forward vector.
  93625. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93626. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93627. };
  93628. /**
  93629. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93630. */
  93631. FramingBehavior.prototype._clearAnimationLocks = function () {
  93632. this._betaIsAnimating = false;
  93633. };
  93634. /**
  93635. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93636. */
  93637. FramingBehavior.prototype._applyUserInteraction = function () {
  93638. if (this.isUserIsMoving) {
  93639. this._lastInteractionTime = BABYLON.Tools.Now;
  93640. this.stopAllAnimations();
  93641. this._clearAnimationLocks();
  93642. }
  93643. };
  93644. /**
  93645. * Stops and removes all animations that have been applied to the camera
  93646. */
  93647. FramingBehavior.prototype.stopAllAnimations = function () {
  93648. if (this._attachedCamera) {
  93649. this._attachedCamera.animations = [];
  93650. }
  93651. while (this._animatables.length) {
  93652. if (this._animatables[0]) {
  93653. this._animatables[0].onAnimationEnd = null;
  93654. this._animatables[0].stop();
  93655. }
  93656. this._animatables.shift();
  93657. }
  93658. };
  93659. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93660. /**
  93661. * Gets a value indicating if the user is moving the camera
  93662. */
  93663. get: function () {
  93664. if (!this._attachedCamera) {
  93665. return false;
  93666. }
  93667. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93668. this._attachedCamera.inertialBetaOffset !== 0 ||
  93669. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93670. this._attachedCamera.inertialPanningX !== 0 ||
  93671. this._attachedCamera.inertialPanningY !== 0 ||
  93672. this._isPointerDown;
  93673. },
  93674. enumerable: true,
  93675. configurable: true
  93676. });
  93677. /**
  93678. * The easing function used by animations
  93679. */
  93680. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93681. /**
  93682. * The easing mode used by animations
  93683. */
  93684. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93685. // Statics
  93686. /**
  93687. * The camera can move all the way towards the mesh.
  93688. */
  93689. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93690. /**
  93691. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93692. */
  93693. FramingBehavior.FitFrustumSidesMode = 1;
  93694. return FramingBehavior;
  93695. }());
  93696. BABYLON.FramingBehavior = FramingBehavior;
  93697. })(BABYLON || (BABYLON = {}));
  93698. //# sourceMappingURL=babylon.framingBehavior.js.map
  93699. var BABYLON;
  93700. (function (BABYLON) {
  93701. /**
  93702. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93703. */
  93704. var BouncingBehavior = /** @class */ (function () {
  93705. function BouncingBehavior() {
  93706. /**
  93707. * The duration of the animation, in milliseconds
  93708. */
  93709. this.transitionDuration = 450;
  93710. /**
  93711. * Length of the distance animated by the transition when lower radius is reached
  93712. */
  93713. this.lowerRadiusTransitionRange = 2;
  93714. /**
  93715. * Length of the distance animated by the transition when upper radius is reached
  93716. */
  93717. this.upperRadiusTransitionRange = -2;
  93718. this._autoTransitionRange = false;
  93719. // Animations
  93720. this._radiusIsAnimating = false;
  93721. this._radiusBounceTransition = null;
  93722. this._animatables = new Array();
  93723. }
  93724. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93725. get: function () {
  93726. return "Bouncing";
  93727. },
  93728. enumerable: true,
  93729. configurable: true
  93730. });
  93731. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93732. /**
  93733. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93734. */
  93735. get: function () {
  93736. return this._autoTransitionRange;
  93737. },
  93738. /**
  93739. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93740. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93741. */
  93742. set: function (value) {
  93743. var _this = this;
  93744. if (this._autoTransitionRange === value) {
  93745. return;
  93746. }
  93747. this._autoTransitionRange = value;
  93748. var camera = this._attachedCamera;
  93749. if (!camera) {
  93750. return;
  93751. }
  93752. if (value) {
  93753. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93754. if (!mesh) {
  93755. return;
  93756. }
  93757. mesh.computeWorldMatrix(true);
  93758. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93759. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93760. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93761. });
  93762. }
  93763. else if (this._onMeshTargetChangedObserver) {
  93764. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93765. }
  93766. },
  93767. enumerable: true,
  93768. configurable: true
  93769. });
  93770. BouncingBehavior.prototype.init = function () {
  93771. // Do notihng
  93772. };
  93773. BouncingBehavior.prototype.attach = function (camera) {
  93774. var _this = this;
  93775. this._attachedCamera = camera;
  93776. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93777. if (!_this._attachedCamera) {
  93778. return;
  93779. }
  93780. // Add the bounce animation to the lower radius limit
  93781. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93782. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93783. }
  93784. // Add the bounce animation to the upper radius limit
  93785. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93786. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93787. }
  93788. });
  93789. };
  93790. BouncingBehavior.prototype.detach = function () {
  93791. if (!this._attachedCamera) {
  93792. return;
  93793. }
  93794. if (this._onAfterCheckInputsObserver) {
  93795. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93796. }
  93797. if (this._onMeshTargetChangedObserver) {
  93798. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93799. }
  93800. this._attachedCamera = null;
  93801. };
  93802. /**
  93803. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93804. * @param radiusLimit The limit to check against.
  93805. * @return Bool to indicate if at limit.
  93806. */
  93807. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  93808. if (!this._attachedCamera) {
  93809. return false;
  93810. }
  93811. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  93812. return true;
  93813. }
  93814. return false;
  93815. };
  93816. /**
  93817. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  93818. * @param radiusDelta The delta by which to animate to. Can be negative.
  93819. */
  93820. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  93821. var _this = this;
  93822. if (!this._attachedCamera) {
  93823. return;
  93824. }
  93825. if (!this._radiusBounceTransition) {
  93826. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  93827. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  93828. }
  93829. // Prevent zoom until bounce has completed
  93830. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  93831. this._attachedCamera.wheelPrecision = Infinity;
  93832. this._attachedCamera.inertialRadiusOffset = 0;
  93833. // Animate to the radius limit
  93834. this.stopAllAnimations();
  93835. this._radiusIsAnimating = true;
  93836. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  93837. if (animatable) {
  93838. this._animatables.push(animatable);
  93839. }
  93840. };
  93841. /**
  93842. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  93843. */
  93844. BouncingBehavior.prototype._clearAnimationLocks = function () {
  93845. this._radiusIsAnimating = false;
  93846. if (this._attachedCamera) {
  93847. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  93848. }
  93849. };
  93850. /**
  93851. * Stops and removes all animations that have been applied to the camera
  93852. */
  93853. BouncingBehavior.prototype.stopAllAnimations = function () {
  93854. if (this._attachedCamera) {
  93855. this._attachedCamera.animations = [];
  93856. }
  93857. while (this._animatables.length) {
  93858. this._animatables[0].onAnimationEnd = null;
  93859. this._animatables[0].stop();
  93860. this._animatables.shift();
  93861. }
  93862. };
  93863. /**
  93864. * The easing function used by animations
  93865. */
  93866. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  93867. /**
  93868. * The easing mode used by animations
  93869. */
  93870. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  93871. return BouncingBehavior;
  93872. }());
  93873. BABYLON.BouncingBehavior = BouncingBehavior;
  93874. })(BABYLON || (BABYLON = {}));
  93875. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  93876. var BABYLON;
  93877. (function (BABYLON) {
  93878. var AutoRotationBehavior = /** @class */ (function () {
  93879. function AutoRotationBehavior() {
  93880. this._zoomStopsAnimation = false;
  93881. this._idleRotationSpeed = 0.05;
  93882. this._idleRotationWaitTime = 2000;
  93883. this._idleRotationSpinupTime = 2000;
  93884. this._isPointerDown = false;
  93885. this._lastFrameTime = null;
  93886. this._lastInteractionTime = -Infinity;
  93887. this._cameraRotationSpeed = 0;
  93888. this._lastFrameRadius = 0;
  93889. }
  93890. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  93891. get: function () {
  93892. return "AutoRotation";
  93893. },
  93894. enumerable: true,
  93895. configurable: true
  93896. });
  93897. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  93898. /**
  93899. * Gets the flag that indicates if user zooming should stop animation.
  93900. */
  93901. get: function () {
  93902. return this._zoomStopsAnimation;
  93903. },
  93904. /**
  93905. * Sets the flag that indicates if user zooming should stop animation.
  93906. */
  93907. set: function (flag) {
  93908. this._zoomStopsAnimation = flag;
  93909. },
  93910. enumerable: true,
  93911. configurable: true
  93912. });
  93913. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  93914. /**
  93915. * Gets the default speed at which the camera rotates around the model.
  93916. */
  93917. get: function () {
  93918. return this._idleRotationSpeed;
  93919. },
  93920. /**
  93921. * Sets the default speed at which the camera rotates around the model.
  93922. */
  93923. set: function (speed) {
  93924. this._idleRotationSpeed = speed;
  93925. },
  93926. enumerable: true,
  93927. configurable: true
  93928. });
  93929. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  93930. /**
  93931. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  93932. */
  93933. get: function () {
  93934. return this._idleRotationWaitTime;
  93935. },
  93936. /**
  93937. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  93938. */
  93939. set: function (time) {
  93940. this._idleRotationWaitTime = time;
  93941. },
  93942. enumerable: true,
  93943. configurable: true
  93944. });
  93945. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  93946. /**
  93947. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93948. */
  93949. get: function () {
  93950. return this._idleRotationSpinupTime;
  93951. },
  93952. /**
  93953. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  93954. */
  93955. set: function (time) {
  93956. this._idleRotationSpinupTime = time;
  93957. },
  93958. enumerable: true,
  93959. configurable: true
  93960. });
  93961. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  93962. /**
  93963. * Gets a value indicating if the camera is currently rotating because of this behavior
  93964. */
  93965. get: function () {
  93966. return Math.abs(this._cameraRotationSpeed) > 0;
  93967. },
  93968. enumerable: true,
  93969. configurable: true
  93970. });
  93971. AutoRotationBehavior.prototype.init = function () {
  93972. // Do notihng
  93973. };
  93974. AutoRotationBehavior.prototype.attach = function (camera) {
  93975. var _this = this;
  93976. this._attachedCamera = camera;
  93977. var scene = this._attachedCamera.getScene();
  93978. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93979. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93980. _this._isPointerDown = true;
  93981. return;
  93982. }
  93983. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93984. _this._isPointerDown = false;
  93985. }
  93986. });
  93987. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93988. var now = BABYLON.Tools.Now;
  93989. var dt = 0;
  93990. if (_this._lastFrameTime != null) {
  93991. dt = now - _this._lastFrameTime;
  93992. }
  93993. _this._lastFrameTime = now;
  93994. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93995. _this._applyUserInteraction();
  93996. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  93997. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  93998. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  93999. // Step camera rotation by rotation speed
  94000. if (_this._attachedCamera) {
  94001. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94002. }
  94003. });
  94004. };
  94005. AutoRotationBehavior.prototype.detach = function () {
  94006. if (!this._attachedCamera) {
  94007. return;
  94008. }
  94009. var scene = this._attachedCamera.getScene();
  94010. if (this._onPrePointerObservableObserver) {
  94011. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94012. }
  94013. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94014. this._attachedCamera = null;
  94015. };
  94016. /**
  94017. * Returns true if user is scrolling.
  94018. * @return true if user is scrolling.
  94019. */
  94020. AutoRotationBehavior.prototype._userIsZooming = function () {
  94021. if (!this._attachedCamera) {
  94022. return false;
  94023. }
  94024. return this._attachedCamera.inertialRadiusOffset !== 0;
  94025. };
  94026. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94027. if (!this._attachedCamera) {
  94028. return false;
  94029. }
  94030. var zoomHasHitLimit = false;
  94031. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94032. zoomHasHitLimit = true;
  94033. }
  94034. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94035. this._lastFrameRadius = this._attachedCamera.radius;
  94036. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94037. };
  94038. /**
  94039. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94040. */
  94041. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94042. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94043. this._lastInteractionTime = BABYLON.Tools.Now;
  94044. }
  94045. };
  94046. // Tools
  94047. AutoRotationBehavior.prototype._userIsMoving = function () {
  94048. if (!this._attachedCamera) {
  94049. return false;
  94050. }
  94051. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94052. this._attachedCamera.inertialBetaOffset !== 0 ||
  94053. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94054. this._attachedCamera.inertialPanningX !== 0 ||
  94055. this._attachedCamera.inertialPanningY !== 0 ||
  94056. this._isPointerDown;
  94057. };
  94058. return AutoRotationBehavior;
  94059. }());
  94060. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94061. })(BABYLON || (BABYLON = {}));
  94062. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94063. var BABYLON;
  94064. (function (BABYLON) {
  94065. var NullEngineOptions = /** @class */ (function () {
  94066. function NullEngineOptions() {
  94067. this.renderWidth = 512;
  94068. this.renderHeight = 256;
  94069. this.textureSize = 512;
  94070. this.deterministicLockstep = false;
  94071. this.lockstepMaxSteps = 4;
  94072. }
  94073. return NullEngineOptions;
  94074. }());
  94075. BABYLON.NullEngineOptions = NullEngineOptions;
  94076. /**
  94077. * The null engine class provides support for headless version of babylon.js.
  94078. * This can be used in server side scenario or for testing purposes
  94079. */
  94080. var NullEngine = /** @class */ (function (_super) {
  94081. __extends(NullEngine, _super);
  94082. function NullEngine(options) {
  94083. if (options === void 0) { options = new NullEngineOptions(); }
  94084. var _this = _super.call(this, null) || this;
  94085. if (options.deterministicLockstep === undefined) {
  94086. options.deterministicLockstep = false;
  94087. }
  94088. if (options.lockstepMaxSteps === undefined) {
  94089. options.lockstepMaxSteps = 4;
  94090. }
  94091. _this._options = options;
  94092. // Init caps
  94093. // We consider we are on a webgl1 capable device
  94094. _this._caps = new BABYLON.EngineCapabilities();
  94095. _this._caps.maxTexturesImageUnits = 16;
  94096. _this._caps.maxVertexTextureImageUnits = 16;
  94097. _this._caps.maxTextureSize = 512;
  94098. _this._caps.maxCubemapTextureSize = 512;
  94099. _this._caps.maxRenderTextureSize = 512;
  94100. _this._caps.maxVertexAttribs = 16;
  94101. _this._caps.maxVaryingVectors = 16;
  94102. _this._caps.maxFragmentUniformVectors = 16;
  94103. _this._caps.maxVertexUniformVectors = 16;
  94104. // Extensions
  94105. _this._caps.standardDerivatives = false;
  94106. _this._caps.astc = null;
  94107. _this._caps.s3tc = null;
  94108. _this._caps.pvrtc = null;
  94109. _this._caps.etc1 = null;
  94110. _this._caps.etc2 = null;
  94111. _this._caps.textureAnisotropicFilterExtension = null;
  94112. _this._caps.maxAnisotropy = 0;
  94113. _this._caps.uintIndices = false;
  94114. _this._caps.fragmentDepthSupported = false;
  94115. _this._caps.highPrecisionShaderSupported = true;
  94116. _this._caps.colorBufferFloat = false;
  94117. _this._caps.textureFloat = false;
  94118. _this._caps.textureFloatLinearFiltering = false;
  94119. _this._caps.textureFloatRender = false;
  94120. _this._caps.textureHalfFloat = false;
  94121. _this._caps.textureHalfFloatLinearFiltering = false;
  94122. _this._caps.textureHalfFloatRender = false;
  94123. _this._caps.textureLOD = false;
  94124. _this._caps.drawBuffersExtension = false;
  94125. _this._caps.depthTextureExtension = false;
  94126. _this._caps.vertexArrayObject = false;
  94127. _this._caps.instancedArrays = false;
  94128. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94129. // Wrappers
  94130. if (typeof URL === "undefined") {
  94131. URL = {
  94132. createObjectURL: function () { },
  94133. revokeObjectURL: function () { }
  94134. };
  94135. }
  94136. if (typeof Blob === "undefined") {
  94137. Blob = function () { };
  94138. }
  94139. return _this;
  94140. }
  94141. NullEngine.prototype.isDeterministicLockStep = function () {
  94142. return this._options.deterministicLockstep;
  94143. };
  94144. NullEngine.prototype.getLockstepMaxSteps = function () {
  94145. return this._options.lockstepMaxSteps;
  94146. };
  94147. NullEngine.prototype.getHardwareScalingLevel = function () {
  94148. return 1.0;
  94149. };
  94150. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94151. return {
  94152. capacity: 0,
  94153. references: 1,
  94154. is32Bits: false
  94155. };
  94156. };
  94157. NullEngine.prototype.createIndexBuffer = function (indices) {
  94158. return {
  94159. capacity: 0,
  94160. references: 1,
  94161. is32Bits: false
  94162. };
  94163. };
  94164. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94165. if (stencil === void 0) { stencil = false; }
  94166. };
  94167. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94168. if (useScreen === void 0) { useScreen = false; }
  94169. if (!useScreen && this._currentRenderTarget) {
  94170. return this._currentRenderTarget.width;
  94171. }
  94172. return this._options.renderWidth;
  94173. };
  94174. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94175. if (useScreen === void 0) { useScreen = false; }
  94176. if (!useScreen && this._currentRenderTarget) {
  94177. return this._currentRenderTarget.height;
  94178. }
  94179. return this._options.renderHeight;
  94180. };
  94181. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94182. this._cachedViewport = viewport;
  94183. };
  94184. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94185. return {
  94186. transformFeedback: null,
  94187. __SPECTOR_rebuildProgram: null
  94188. };
  94189. };
  94190. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94191. return [];
  94192. };
  94193. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94194. return [];
  94195. };
  94196. NullEngine.prototype.bindSamplers = function (effect) {
  94197. this._currentEffect = null;
  94198. };
  94199. NullEngine.prototype.enableEffect = function (effect) {
  94200. this._currentEffect = effect;
  94201. if (effect.onBind) {
  94202. effect.onBind(effect);
  94203. }
  94204. effect.onBindObservable.notifyObservers(effect);
  94205. };
  94206. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94207. if (zOffset === void 0) { zOffset = 0; }
  94208. if (reverseSide === void 0) { reverseSide = false; }
  94209. };
  94210. NullEngine.prototype.setIntArray = function (uniform, array) {
  94211. };
  94212. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94213. };
  94214. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94215. };
  94216. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94217. };
  94218. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94219. };
  94220. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94221. };
  94222. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94223. };
  94224. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94225. };
  94226. NullEngine.prototype.setArray = function (uniform, array) {
  94227. };
  94228. NullEngine.prototype.setArray2 = function (uniform, array) {
  94229. };
  94230. NullEngine.prototype.setArray3 = function (uniform, array) {
  94231. };
  94232. NullEngine.prototype.setArray4 = function (uniform, array) {
  94233. };
  94234. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94235. };
  94236. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94237. };
  94238. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94239. };
  94240. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94241. };
  94242. NullEngine.prototype.setFloat = function (uniform, value) {
  94243. };
  94244. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94245. };
  94246. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94247. };
  94248. NullEngine.prototype.setBool = function (uniform, bool) {
  94249. };
  94250. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94251. };
  94252. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94253. };
  94254. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94255. };
  94256. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94257. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94258. if (this._alphaMode === mode) {
  94259. return;
  94260. }
  94261. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94262. if (!noDepthWriteChange) {
  94263. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94264. }
  94265. this._alphaMode = mode;
  94266. };
  94267. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94268. };
  94269. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94270. if (this.preventCacheWipeBetweenFrames) {
  94271. return;
  94272. }
  94273. this.resetTextureCache();
  94274. this._currentEffect = null;
  94275. if (bruteForce) {
  94276. this._currentProgram = null;
  94277. this._stencilState.reset();
  94278. this._depthCullingState.reset();
  94279. this._alphaState.reset();
  94280. }
  94281. this._cachedVertexBuffers = null;
  94282. this._cachedIndexBuffer = null;
  94283. this._cachedEffectForVertexBuffers = null;
  94284. };
  94285. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94286. };
  94287. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94288. };
  94289. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94290. };
  94291. NullEngine.prototype._createTexture = function () {
  94292. return {};
  94293. };
  94294. NullEngine.prototype._releaseTexture = function (texture) {
  94295. };
  94296. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94297. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94298. if (onLoad === void 0) { onLoad = null; }
  94299. if (onError === void 0) { onError = null; }
  94300. if (buffer === void 0) { buffer = null; }
  94301. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94302. var url = String(urlArg);
  94303. texture.url = url;
  94304. texture.generateMipMaps = !noMipmap;
  94305. texture.samplingMode = samplingMode;
  94306. texture.invertY = invertY;
  94307. texture.baseWidth = this._options.textureSize;
  94308. texture.baseHeight = this._options.textureSize;
  94309. texture.width = this._options.textureSize;
  94310. texture.height = this._options.textureSize;
  94311. if (format) {
  94312. texture.format = format;
  94313. }
  94314. texture.isReady = true;
  94315. if (onLoad) {
  94316. onLoad();
  94317. }
  94318. return texture;
  94319. };
  94320. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94321. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94322. if (options !== undefined && typeof options === "object") {
  94323. fullOptions.generateMipMaps = options.generateMipMaps;
  94324. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94325. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94326. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  94327. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  94328. }
  94329. else {
  94330. fullOptions.generateMipMaps = options;
  94331. fullOptions.generateDepthBuffer = true;
  94332. fullOptions.generateStencilBuffer = false;
  94333. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94334. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  94335. }
  94336. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  94337. var width = size.width || size;
  94338. var height = size.height || size;
  94339. texture._depthStencilBuffer = {};
  94340. texture._framebuffer = {};
  94341. texture.baseWidth = width;
  94342. texture.baseHeight = height;
  94343. texture.width = width;
  94344. texture.height = height;
  94345. texture.isReady = true;
  94346. texture.samples = 1;
  94347. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  94348. texture.samplingMode = fullOptions.samplingMode;
  94349. texture.type = fullOptions.type;
  94350. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  94351. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  94352. return texture;
  94353. };
  94354. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  94355. texture.samplingMode = samplingMode;
  94356. };
  94357. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  94358. if (this._currentRenderTarget) {
  94359. this.unBindFramebuffer(this._currentRenderTarget);
  94360. }
  94361. this._currentRenderTarget = texture;
  94362. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  94363. if (this._cachedViewport && !forceFullscreenViewport) {
  94364. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  94365. }
  94366. };
  94367. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  94368. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  94369. this._currentRenderTarget = null;
  94370. if (onBeforeUnbind) {
  94371. if (texture._MSAAFramebuffer) {
  94372. this._currentFramebuffer = texture._framebuffer;
  94373. }
  94374. onBeforeUnbind();
  94375. }
  94376. this._currentFramebuffer = null;
  94377. };
  94378. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  94379. var vbo = {
  94380. capacity: 1,
  94381. references: 1,
  94382. is32Bits: false
  94383. };
  94384. return vbo;
  94385. };
  94386. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  94387. if (offset === void 0) { offset = 0; }
  94388. };
  94389. /**
  94390. * Updates a dynamic vertex buffer.
  94391. * @param vertexBuffer the vertex buffer to update
  94392. * @param data the data used to update the vertex buffer
  94393. * @param byteOffset the byte offset of the data (optional)
  94394. * @param byteLength the byte length of the data (optional)
  94395. */
  94396. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  94397. };
  94398. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  94399. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  94400. this._boundTexturesCache[this._activeChannel] = texture;
  94401. }
  94402. };
  94403. NullEngine.prototype._bindTexture = function (channel, texture) {
  94404. if (channel < 0) {
  94405. return;
  94406. }
  94407. this._bindTextureDirectly(0, texture);
  94408. };
  94409. NullEngine.prototype._releaseBuffer = function (buffer) {
  94410. buffer.references--;
  94411. if (buffer.references === 0) {
  94412. return true;
  94413. }
  94414. return false;
  94415. };
  94416. return NullEngine;
  94417. }(BABYLON.Engine));
  94418. BABYLON.NullEngine = NullEngine;
  94419. })(BABYLON || (BABYLON = {}));
  94420. //# sourceMappingURL=babylon.nullEngine.js.map
  94421. var BABYLON;
  94422. (function (BABYLON) {
  94423. /**
  94424. * This class can be used to get instrumentation data from a Babylon engine
  94425. */
  94426. var EngineInstrumentation = /** @class */ (function () {
  94427. function EngineInstrumentation(engine) {
  94428. this.engine = engine;
  94429. this._captureGPUFrameTime = false;
  94430. this._gpuFrameTime = new BABYLON.PerfCounter();
  94431. this._captureShaderCompilationTime = false;
  94432. this._shaderCompilationTime = new BABYLON.PerfCounter();
  94433. // Observers
  94434. this._onBeginFrameObserver = null;
  94435. this._onEndFrameObserver = null;
  94436. this._onBeforeShaderCompilationObserver = null;
  94437. this._onAfterShaderCompilationObserver = null;
  94438. }
  94439. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  94440. // Properties
  94441. /**
  94442. * Gets the perf counter used for GPU frame time
  94443. */
  94444. get: function () {
  94445. return this._gpuFrameTime;
  94446. },
  94447. enumerable: true,
  94448. configurable: true
  94449. });
  94450. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  94451. /**
  94452. * Gets the GPU frame time capture status
  94453. */
  94454. get: function () {
  94455. return this._captureGPUFrameTime;
  94456. },
  94457. /**
  94458. * Enable or disable the GPU frame time capture
  94459. */
  94460. set: function (value) {
  94461. var _this = this;
  94462. if (value === this._captureGPUFrameTime) {
  94463. return;
  94464. }
  94465. this._captureGPUFrameTime = value;
  94466. if (value) {
  94467. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  94468. if (!_this._gpuFrameTimeToken) {
  94469. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  94470. }
  94471. });
  94472. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  94473. if (!_this._gpuFrameTimeToken) {
  94474. return;
  94475. }
  94476. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  94477. if (time > -1) {
  94478. _this._gpuFrameTimeToken = null;
  94479. _this._gpuFrameTime.fetchNewFrame();
  94480. _this._gpuFrameTime.addCount(time, true);
  94481. }
  94482. });
  94483. }
  94484. else {
  94485. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94486. this._onBeginFrameObserver = null;
  94487. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94488. this._onEndFrameObserver = null;
  94489. }
  94490. },
  94491. enumerable: true,
  94492. configurable: true
  94493. });
  94494. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  94495. /**
  94496. * Gets the perf counter used for shader compilation time
  94497. */
  94498. get: function () {
  94499. return this._shaderCompilationTime;
  94500. },
  94501. enumerable: true,
  94502. configurable: true
  94503. });
  94504. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  94505. /**
  94506. * Gets the shader compilation time capture status
  94507. */
  94508. get: function () {
  94509. return this._captureShaderCompilationTime;
  94510. },
  94511. /**
  94512. * Enable or disable the shader compilation time capture
  94513. */
  94514. set: function (value) {
  94515. var _this = this;
  94516. if (value === this._captureShaderCompilationTime) {
  94517. return;
  94518. }
  94519. this._captureShaderCompilationTime = value;
  94520. if (value) {
  94521. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  94522. _this._shaderCompilationTime.fetchNewFrame();
  94523. _this._shaderCompilationTime.beginMonitoring();
  94524. });
  94525. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  94526. _this._shaderCompilationTime.endMonitoring();
  94527. });
  94528. }
  94529. else {
  94530. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94531. this._onBeforeShaderCompilationObserver = null;
  94532. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94533. this._onAfterShaderCompilationObserver = null;
  94534. }
  94535. },
  94536. enumerable: true,
  94537. configurable: true
  94538. });
  94539. EngineInstrumentation.prototype.dispose = function () {
  94540. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94541. this._onBeginFrameObserver = null;
  94542. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94543. this._onEndFrameObserver = null;
  94544. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94545. this._onBeforeShaderCompilationObserver = null;
  94546. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94547. this._onAfterShaderCompilationObserver = null;
  94548. this.engine = null;
  94549. };
  94550. return EngineInstrumentation;
  94551. }());
  94552. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94553. })(BABYLON || (BABYLON = {}));
  94554. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94555. var BABYLON;
  94556. (function (BABYLON) {
  94557. /**
  94558. * This class can be used to get instrumentation data from a Babylon engine
  94559. */
  94560. var SceneInstrumentation = /** @class */ (function () {
  94561. function SceneInstrumentation(scene) {
  94562. var _this = this;
  94563. this.scene = scene;
  94564. this._captureActiveMeshesEvaluationTime = false;
  94565. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94566. this._captureRenderTargetsRenderTime = false;
  94567. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94568. this._captureFrameTime = false;
  94569. this._frameTime = new BABYLON.PerfCounter();
  94570. this._captureRenderTime = false;
  94571. this._renderTime = new BABYLON.PerfCounter();
  94572. this._captureInterFrameTime = false;
  94573. this._interFrameTime = new BABYLON.PerfCounter();
  94574. this._captureParticlesRenderTime = false;
  94575. this._particlesRenderTime = new BABYLON.PerfCounter();
  94576. this._captureSpritesRenderTime = false;
  94577. this._spritesRenderTime = new BABYLON.PerfCounter();
  94578. this._capturePhysicsTime = false;
  94579. this._physicsTime = new BABYLON.PerfCounter();
  94580. this._captureAnimationsTime = false;
  94581. this._animationsTime = new BABYLON.PerfCounter();
  94582. // Observers
  94583. this._onBeforeActiveMeshesEvaluationObserver = null;
  94584. this._onAfterActiveMeshesEvaluationObserver = null;
  94585. this._onBeforeRenderTargetsRenderObserver = null;
  94586. this._onAfterRenderTargetsRenderObserver = null;
  94587. this._onAfterRenderObserver = null;
  94588. this._onBeforeDrawPhaseObserver = null;
  94589. this._onAfterDrawPhaseObserver = null;
  94590. this._onBeforeAnimationsObserver = null;
  94591. this._onBeforeParticlesRenderingObserver = null;
  94592. this._onAfterParticlesRenderingObserver = null;
  94593. this._onBeforeSpritesRenderingObserver = null;
  94594. this._onAfterSpritesRenderingObserver = null;
  94595. this._onBeforePhysicsObserver = null;
  94596. this._onAfterPhysicsObserver = null;
  94597. this._onAfterAnimationsObserver = null;
  94598. // Before render
  94599. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94600. if (_this._captureActiveMeshesEvaluationTime) {
  94601. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94602. }
  94603. if (_this._captureRenderTargetsRenderTime) {
  94604. _this._renderTargetsRenderTime.fetchNewFrame();
  94605. }
  94606. if (_this._captureFrameTime) {
  94607. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94608. _this._frameTime.beginMonitoring();
  94609. }
  94610. if (_this._captureInterFrameTime) {
  94611. _this._interFrameTime.endMonitoring();
  94612. }
  94613. if (_this._captureParticlesRenderTime) {
  94614. _this._particlesRenderTime.fetchNewFrame();
  94615. }
  94616. if (_this._captureSpritesRenderTime) {
  94617. _this._spritesRenderTime.fetchNewFrame();
  94618. }
  94619. if (_this._captureAnimationsTime) {
  94620. _this._animationsTime.beginMonitoring();
  94621. }
  94622. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94623. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94624. });
  94625. // After render
  94626. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94627. if (_this._captureFrameTime) {
  94628. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94629. _this._frameTime.endMonitoring();
  94630. }
  94631. if (_this._captureRenderTime) {
  94632. _this._renderTime.endMonitoring(false);
  94633. }
  94634. if (_this._captureInterFrameTime) {
  94635. _this._interFrameTime.beginMonitoring();
  94636. }
  94637. });
  94638. }
  94639. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94640. // Properties
  94641. /**
  94642. * Gets the perf counter used for active meshes evaluation time
  94643. */
  94644. get: function () {
  94645. return this._activeMeshesEvaluationTime;
  94646. },
  94647. enumerable: true,
  94648. configurable: true
  94649. });
  94650. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94651. /**
  94652. * Gets the active meshes evaluation time capture status
  94653. */
  94654. get: function () {
  94655. return this._captureActiveMeshesEvaluationTime;
  94656. },
  94657. /**
  94658. * Enable or disable the active meshes evaluation time capture
  94659. */
  94660. set: function (value) {
  94661. var _this = this;
  94662. if (value === this._captureActiveMeshesEvaluationTime) {
  94663. return;
  94664. }
  94665. this._captureActiveMeshesEvaluationTime = value;
  94666. if (value) {
  94667. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94668. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94669. _this._activeMeshesEvaluationTime.beginMonitoring();
  94670. });
  94671. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94672. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94673. _this._activeMeshesEvaluationTime.endMonitoring();
  94674. });
  94675. }
  94676. else {
  94677. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94678. this._onBeforeActiveMeshesEvaluationObserver = null;
  94679. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94680. this._onAfterActiveMeshesEvaluationObserver = null;
  94681. }
  94682. },
  94683. enumerable: true,
  94684. configurable: true
  94685. });
  94686. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94687. /**
  94688. * Gets the perf counter used for render targets render time
  94689. */
  94690. get: function () {
  94691. return this._renderTargetsRenderTime;
  94692. },
  94693. enumerable: true,
  94694. configurable: true
  94695. });
  94696. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94697. /**
  94698. * Gets the render targets render time capture status
  94699. */
  94700. get: function () {
  94701. return this._captureRenderTargetsRenderTime;
  94702. },
  94703. /**
  94704. * Enable or disable the render targets render time capture
  94705. */
  94706. set: function (value) {
  94707. var _this = this;
  94708. if (value === this._captureRenderTargetsRenderTime) {
  94709. return;
  94710. }
  94711. this._captureRenderTargetsRenderTime = value;
  94712. if (value) {
  94713. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94714. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94715. _this._renderTargetsRenderTime.beginMonitoring();
  94716. });
  94717. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94718. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94719. _this._renderTargetsRenderTime.endMonitoring(false);
  94720. });
  94721. }
  94722. else {
  94723. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94724. this._onBeforeRenderTargetsRenderObserver = null;
  94725. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94726. this._onAfterRenderTargetsRenderObserver = null;
  94727. }
  94728. },
  94729. enumerable: true,
  94730. configurable: true
  94731. });
  94732. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94733. /**
  94734. * Gets the perf counter used for particles render time
  94735. */
  94736. get: function () {
  94737. return this._particlesRenderTime;
  94738. },
  94739. enumerable: true,
  94740. configurable: true
  94741. });
  94742. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94743. /**
  94744. * Gets the particles render time capture status
  94745. */
  94746. get: function () {
  94747. return this._captureParticlesRenderTime;
  94748. },
  94749. /**
  94750. * Enable or disable the particles render time capture
  94751. */
  94752. set: function (value) {
  94753. var _this = this;
  94754. if (value === this._captureParticlesRenderTime) {
  94755. return;
  94756. }
  94757. this._captureParticlesRenderTime = value;
  94758. if (value) {
  94759. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94760. BABYLON.Tools.StartPerformanceCounter("Particles");
  94761. _this._particlesRenderTime.beginMonitoring();
  94762. });
  94763. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94764. BABYLON.Tools.EndPerformanceCounter("Particles");
  94765. _this._particlesRenderTime.endMonitoring(false);
  94766. });
  94767. }
  94768. else {
  94769. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94770. this._onBeforeParticlesRenderingObserver = null;
  94771. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94772. this._onAfterParticlesRenderingObserver = null;
  94773. }
  94774. },
  94775. enumerable: true,
  94776. configurable: true
  94777. });
  94778. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94779. /**
  94780. * Gets the perf counter used for sprites render time
  94781. */
  94782. get: function () {
  94783. return this._spritesRenderTime;
  94784. },
  94785. enumerable: true,
  94786. configurable: true
  94787. });
  94788. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94789. /**
  94790. * Gets the sprites render time capture status
  94791. */
  94792. get: function () {
  94793. return this._captureSpritesRenderTime;
  94794. },
  94795. /**
  94796. * Enable or disable the sprites render time capture
  94797. */
  94798. set: function (value) {
  94799. var _this = this;
  94800. if (value === this._captureSpritesRenderTime) {
  94801. return;
  94802. }
  94803. this._captureSpritesRenderTime = value;
  94804. if (value) {
  94805. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94806. BABYLON.Tools.StartPerformanceCounter("Sprites");
  94807. _this._spritesRenderTime.beginMonitoring();
  94808. });
  94809. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  94810. BABYLON.Tools.EndPerformanceCounter("Sprites");
  94811. _this._spritesRenderTime.endMonitoring(false);
  94812. });
  94813. }
  94814. else {
  94815. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  94816. this._onBeforeSpritesRenderingObserver = null;
  94817. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  94818. this._onAfterSpritesRenderingObserver = null;
  94819. }
  94820. },
  94821. enumerable: true,
  94822. configurable: true
  94823. });
  94824. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  94825. /**
  94826. * Gets the perf counter used for physics time
  94827. */
  94828. get: function () {
  94829. return this._physicsTime;
  94830. },
  94831. enumerable: true,
  94832. configurable: true
  94833. });
  94834. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  94835. /**
  94836. * Gets the physics time capture status
  94837. */
  94838. get: function () {
  94839. return this._capturePhysicsTime;
  94840. },
  94841. /**
  94842. * Enable or disable the physics time capture
  94843. */
  94844. set: function (value) {
  94845. var _this = this;
  94846. if (value === this._capturePhysicsTime) {
  94847. return;
  94848. }
  94849. this._capturePhysicsTime = value;
  94850. if (value) {
  94851. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  94852. BABYLON.Tools.StartPerformanceCounter("Physics");
  94853. _this._physicsTime.beginMonitoring();
  94854. });
  94855. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  94856. BABYLON.Tools.EndPerformanceCounter("Physics");
  94857. _this._physicsTime.endMonitoring();
  94858. });
  94859. }
  94860. else {
  94861. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  94862. this._onBeforePhysicsObserver = null;
  94863. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  94864. this._onAfterPhysicsObserver = null;
  94865. }
  94866. },
  94867. enumerable: true,
  94868. configurable: true
  94869. });
  94870. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  94871. /**
  94872. * Gets the perf counter used for animations time
  94873. */
  94874. get: function () {
  94875. return this._animationsTime;
  94876. },
  94877. enumerable: true,
  94878. configurable: true
  94879. });
  94880. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  94881. /**
  94882. * Gets the animations time capture status
  94883. */
  94884. get: function () {
  94885. return this._captureAnimationsTime;
  94886. },
  94887. /**
  94888. * Enable or disable the animations time capture
  94889. */
  94890. set: function (value) {
  94891. var _this = this;
  94892. if (value === this._captureAnimationsTime) {
  94893. return;
  94894. }
  94895. this._captureAnimationsTime = value;
  94896. if (value) {
  94897. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  94898. _this._animationsTime.endMonitoring();
  94899. });
  94900. }
  94901. else {
  94902. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  94903. this._onAfterAnimationsObserver = null;
  94904. }
  94905. },
  94906. enumerable: true,
  94907. configurable: true
  94908. });
  94909. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  94910. /**
  94911. * Gets the perf counter used for frame time capture
  94912. */
  94913. get: function () {
  94914. return this._frameTime;
  94915. },
  94916. enumerable: true,
  94917. configurable: true
  94918. });
  94919. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  94920. /**
  94921. * Gets the frame time capture status
  94922. */
  94923. get: function () {
  94924. return this._captureFrameTime;
  94925. },
  94926. /**
  94927. * Enable or disable the frame time capture
  94928. */
  94929. set: function (value) {
  94930. this._captureFrameTime = value;
  94931. },
  94932. enumerable: true,
  94933. configurable: true
  94934. });
  94935. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  94936. /**
  94937. * Gets the perf counter used for inter-frames time capture
  94938. */
  94939. get: function () {
  94940. return this._interFrameTime;
  94941. },
  94942. enumerable: true,
  94943. configurable: true
  94944. });
  94945. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  94946. /**
  94947. * Gets the inter-frames time capture status
  94948. */
  94949. get: function () {
  94950. return this._captureInterFrameTime;
  94951. },
  94952. /**
  94953. * Enable or disable the inter-frames time capture
  94954. */
  94955. set: function (value) {
  94956. this._captureInterFrameTime = value;
  94957. },
  94958. enumerable: true,
  94959. configurable: true
  94960. });
  94961. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  94962. /**
  94963. * Gets the perf counter used for render time capture
  94964. */
  94965. get: function () {
  94966. return this._renderTime;
  94967. },
  94968. enumerable: true,
  94969. configurable: true
  94970. });
  94971. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  94972. /**
  94973. * Gets the render time capture status
  94974. */
  94975. get: function () {
  94976. return this._captureRenderTime;
  94977. },
  94978. /**
  94979. * Enable or disable the render time capture
  94980. */
  94981. set: function (value) {
  94982. var _this = this;
  94983. if (value === this._captureRenderTime) {
  94984. return;
  94985. }
  94986. this._captureRenderTime = value;
  94987. if (value) {
  94988. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  94989. _this._renderTime.beginMonitoring();
  94990. BABYLON.Tools.StartPerformanceCounter("Main render");
  94991. });
  94992. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  94993. _this._renderTime.endMonitoring(false);
  94994. BABYLON.Tools.EndPerformanceCounter("Main render");
  94995. });
  94996. }
  94997. else {
  94998. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  94999. this._onBeforeDrawPhaseObserver = null;
  95000. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95001. this._onAfterDrawPhaseObserver = null;
  95002. }
  95003. },
  95004. enumerable: true,
  95005. configurable: true
  95006. });
  95007. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95008. /**
  95009. * Gets the perf counter used for draw calls
  95010. */
  95011. get: function () {
  95012. return this.scene.getEngine()._drawCalls;
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95018. /**
  95019. * Gets the perf counter used for texture collisions
  95020. */
  95021. get: function () {
  95022. return this.scene.getEngine()._textureCollisions;
  95023. },
  95024. enumerable: true,
  95025. configurable: true
  95026. });
  95027. SceneInstrumentation.prototype.dispose = function () {
  95028. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95029. this._onAfterRenderObserver = null;
  95030. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95031. this._onBeforeActiveMeshesEvaluationObserver = null;
  95032. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95033. this._onAfterActiveMeshesEvaluationObserver = null;
  95034. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95035. this._onBeforeRenderTargetsRenderObserver = null;
  95036. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95037. this._onAfterRenderTargetsRenderObserver = null;
  95038. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95039. this._onBeforeAnimationsObserver = null;
  95040. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95041. this._onBeforeParticlesRenderingObserver = null;
  95042. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95043. this._onAfterParticlesRenderingObserver = null;
  95044. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95045. this._onBeforeSpritesRenderingObserver = null;
  95046. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95047. this._onAfterSpritesRenderingObserver = null;
  95048. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95049. this._onBeforeDrawPhaseObserver = null;
  95050. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95051. this._onAfterDrawPhaseObserver = null;
  95052. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95053. this._onBeforePhysicsObserver = null;
  95054. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95055. this._onAfterPhysicsObserver = null;
  95056. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95057. this._onAfterAnimationsObserver = null;
  95058. this.scene = null;
  95059. };
  95060. return SceneInstrumentation;
  95061. }());
  95062. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95063. })(BABYLON || (BABYLON = {}));
  95064. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95065. var BABYLON;
  95066. (function (BABYLON) {
  95067. var _TimeToken = /** @class */ (function () {
  95068. function _TimeToken() {
  95069. this._timeElapsedQueryEnded = false;
  95070. }
  95071. return _TimeToken;
  95072. }());
  95073. BABYLON._TimeToken = _TimeToken;
  95074. })(BABYLON || (BABYLON = {}));
  95075. //# sourceMappingURL=babylon.timeToken.js.map
  95076. var BABYLON;
  95077. (function (BABYLON) {
  95078. /**
  95079. * Background material defines definition.
  95080. * @ignore Mainly internal Use
  95081. */
  95082. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95083. __extends(BackgroundMaterialDefines, _super);
  95084. /**
  95085. * Constructor of the defines.
  95086. */
  95087. function BackgroundMaterialDefines() {
  95088. var _this = _super.call(this) || this;
  95089. /**
  95090. * True if the diffuse texture is in use.
  95091. */
  95092. _this.DIFFUSE = false;
  95093. /**
  95094. * The direct UV channel to use.
  95095. */
  95096. _this.DIFFUSEDIRECTUV = 0;
  95097. /**
  95098. * True if the diffuse texture is in gamma space.
  95099. */
  95100. _this.GAMMADIFFUSE = false;
  95101. /**
  95102. * True if the diffuse texture has opacity in the alpha channel.
  95103. */
  95104. _this.DIFFUSEHASALPHA = false;
  95105. /**
  95106. * True if you want the material to fade to transparent at grazing angle.
  95107. */
  95108. _this.OPACITYFRESNEL = false;
  95109. /**
  95110. * True if an extra blur needs to be added in the reflection.
  95111. */
  95112. _this.REFLECTIONBLUR = false;
  95113. /**
  95114. * True if you want the material to fade to reflection at grazing angle.
  95115. */
  95116. _this.REFLECTIONFRESNEL = false;
  95117. /**
  95118. * True if you want the material to falloff as far as you move away from the scene center.
  95119. */
  95120. _this.REFLECTIONFALLOFF = false;
  95121. /**
  95122. * False if the current Webgl implementation does not support the texture lod extension.
  95123. */
  95124. _this.TEXTURELODSUPPORT = false;
  95125. /**
  95126. * True to ensure the data are premultiplied.
  95127. */
  95128. _this.PREMULTIPLYALPHA = false;
  95129. /**
  95130. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95131. */
  95132. _this.USERGBCOLOR = false;
  95133. /**
  95134. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95135. * stays aligned with the desired configuration.
  95136. */
  95137. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95138. /**
  95139. * True to add noise in order to reduce the banding effect.
  95140. */
  95141. _this.NOISE = false;
  95142. /**
  95143. * is the reflection texture in BGR color scheme?
  95144. * Mainly used to solve a bug in ios10 video tag
  95145. */
  95146. _this.REFLECTIONBGR = false;
  95147. _this.IMAGEPROCESSING = false;
  95148. _this.VIGNETTE = false;
  95149. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95150. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95151. _this.TONEMAPPING = false;
  95152. _this.CONTRAST = false;
  95153. _this.COLORCURVES = false;
  95154. _this.COLORGRADING = false;
  95155. _this.COLORGRADING3D = false;
  95156. _this.SAMPLER3DGREENDEPTH = false;
  95157. _this.SAMPLER3DBGRMAP = false;
  95158. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95159. _this.EXPOSURE = false;
  95160. // Reflection.
  95161. _this.REFLECTION = false;
  95162. _this.REFLECTIONMAP_3D = false;
  95163. _this.REFLECTIONMAP_SPHERICAL = false;
  95164. _this.REFLECTIONMAP_PLANAR = false;
  95165. _this.REFLECTIONMAP_CUBIC = false;
  95166. _this.REFLECTIONMAP_PROJECTION = false;
  95167. _this.REFLECTIONMAP_SKYBOX = false;
  95168. _this.REFLECTIONMAP_EXPLICIT = false;
  95169. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95170. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95171. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95172. _this.INVERTCUBICMAP = false;
  95173. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95174. _this.LODINREFLECTIONALPHA = false;
  95175. _this.GAMMAREFLECTION = false;
  95176. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95177. // Default BJS.
  95178. _this.MAINUV1 = false;
  95179. _this.MAINUV2 = false;
  95180. _this.UV1 = false;
  95181. _this.UV2 = false;
  95182. _this.CLIPPLANE = false;
  95183. _this.POINTSIZE = false;
  95184. _this.FOG = false;
  95185. _this.NORMAL = false;
  95186. _this.NUM_BONE_INFLUENCERS = 0;
  95187. _this.BonesPerMesh = 0;
  95188. _this.INSTANCES = false;
  95189. _this.SHADOWFLOAT = false;
  95190. _this.rebuild();
  95191. return _this;
  95192. }
  95193. return BackgroundMaterialDefines;
  95194. }(BABYLON.MaterialDefines));
  95195. /**
  95196. * Background material used to create an efficient environement around your scene.
  95197. */
  95198. var BackgroundMaterial = /** @class */ (function (_super) {
  95199. __extends(BackgroundMaterial, _super);
  95200. /**
  95201. * Instantiates a Background Material in the given scene
  95202. * @param name The friendly name of the material
  95203. * @param scene The scene to add the material to
  95204. */
  95205. function BackgroundMaterial(name, scene) {
  95206. var _this = _super.call(this, name, scene) || this;
  95207. /**
  95208. * Key light Color (multiply against the environement texture)
  95209. */
  95210. _this.primaryColor = BABYLON.Color3.White();
  95211. _this._primaryColorShadowLevel = 0;
  95212. _this._primaryColorHighlightLevel = 0;
  95213. /**
  95214. * Reflection Texture used in the material.
  95215. * Should be author in a specific way for the best result (refer to the documentation).
  95216. */
  95217. _this.reflectionTexture = null;
  95218. /**
  95219. * Reflection Texture level of blur.
  95220. *
  95221. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95222. * texture twice.
  95223. */
  95224. _this.reflectionBlur = 0;
  95225. /**
  95226. * Diffuse Texture used in the material.
  95227. * Should be author in a specific way for the best result (refer to the documentation).
  95228. */
  95229. _this.diffuseTexture = null;
  95230. _this._shadowLights = null;
  95231. /**
  95232. * Specify the list of lights casting shadow on the material.
  95233. * All scene shadow lights will be included if null.
  95234. */
  95235. _this.shadowLights = null;
  95236. /**
  95237. * Helps adjusting the shadow to a softer level if required.
  95238. * 0 means black shadows and 1 means no shadows.
  95239. */
  95240. _this.shadowLevel = 0;
  95241. /**
  95242. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95243. * It is usually zero but might be interesting to modify according to your setup.
  95244. */
  95245. _this.sceneCenter = BABYLON.Vector3.Zero();
  95246. /**
  95247. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95248. * This helps ensuring a nice transition when the camera goes under the ground.
  95249. */
  95250. _this.opacityFresnel = true;
  95251. /**
  95252. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95253. * This helps adding a mirror texture on the ground.
  95254. */
  95255. _this.reflectionFresnel = false;
  95256. /**
  95257. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95258. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95259. */
  95260. _this.reflectionFalloffDistance = 0.0;
  95261. /**
  95262. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95263. */
  95264. _this.reflectionAmount = 1.0;
  95265. /**
  95266. * This specifies the weight of the reflection at grazing angle.
  95267. */
  95268. _this.reflectionReflectance0 = 0.05;
  95269. /**
  95270. * This specifies the weight of the reflection at a perpendicular point of view.
  95271. */
  95272. _this.reflectionReflectance90 = 0.5;
  95273. /**
  95274. * Helps to directly use the maps channels instead of their level.
  95275. */
  95276. _this.useRGBColor = true;
  95277. /**
  95278. * This helps reducing the banding effect that could occur on the background.
  95279. */
  95280. _this.enableNoise = false;
  95281. _this._fovMultiplier = 1.0;
  95282. /**
  95283. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95284. */
  95285. _this.useEquirectangularFOV = false;
  95286. _this._maxSimultaneousLights = 4;
  95287. /**
  95288. * Number of Simultaneous lights allowed on the material.
  95289. */
  95290. _this.maxSimultaneousLights = 4;
  95291. /**
  95292. * Keep track of the image processing observer to allow dispose and replace.
  95293. */
  95294. _this._imageProcessingObserver = null;
  95295. /**
  95296. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95297. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95298. */
  95299. _this.switchToBGR = false;
  95300. // Temp values kept as cache in the material.
  95301. _this._renderTargets = new BABYLON.SmartArray(16);
  95302. _this._reflectionControls = BABYLON.Vector4.Zero();
  95303. _this._white = BABYLON.Color3.White();
  95304. _this._primaryShadowColor = BABYLON.Color3.Black();
  95305. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95306. // Setup the default processing configuration to the scene.
  95307. _this._attachImageProcessingConfiguration(null);
  95308. _this.getRenderTargetTextures = function () {
  95309. _this._renderTargets.reset();
  95310. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95311. _this._renderTargets.push(_this._diffuseTexture);
  95312. }
  95313. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95314. _this._renderTargets.push(_this._reflectionTexture);
  95315. }
  95316. return _this._renderTargets;
  95317. };
  95318. return _this;
  95319. }
  95320. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95321. /**
  95322. * Experimental Internal Use Only.
  95323. *
  95324. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  95325. * This acts as a helper to set the primary color to a more "human friendly" value.
  95326. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  95327. * output color as close as possible from the chosen value.
  95328. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  95329. * part of lighting setup.)
  95330. */
  95331. get: function () {
  95332. return this.__perceptualColor;
  95333. },
  95334. set: function (value) {
  95335. this.__perceptualColor = value;
  95336. this._computePrimaryColorFromPerceptualColor();
  95337. this._markAllSubMeshesAsLightsDirty();
  95338. },
  95339. enumerable: true,
  95340. configurable: true
  95341. });
  95342. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  95343. /**
  95344. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  95345. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  95346. */
  95347. get: function () {
  95348. return this._primaryColorShadowLevel;
  95349. },
  95350. set: function (value) {
  95351. this._primaryColorShadowLevel = value;
  95352. this._computePrimaryColors();
  95353. this._markAllSubMeshesAsLightsDirty();
  95354. },
  95355. enumerable: true,
  95356. configurable: true
  95357. });
  95358. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  95359. /**
  95360. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  95361. * The primary color is used at the level chosen to define what the white area would look.
  95362. */
  95363. get: function () {
  95364. return this._primaryColorHighlightLevel;
  95365. },
  95366. set: function (value) {
  95367. this._primaryColorHighlightLevel = value;
  95368. this._computePrimaryColors();
  95369. this._markAllSubMeshesAsLightsDirty();
  95370. },
  95371. enumerable: true,
  95372. configurable: true
  95373. });
  95374. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  95375. /**
  95376. * Sets the reflection reflectance fresnel values according to the default standard
  95377. * empirically know to work well :-)
  95378. */
  95379. set: function (value) {
  95380. var reflectionWeight = value;
  95381. if (reflectionWeight < 0.5) {
  95382. reflectionWeight = reflectionWeight * 2.0;
  95383. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  95384. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  95385. }
  95386. else {
  95387. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  95388. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  95389. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  95390. }
  95391. },
  95392. enumerable: true,
  95393. configurable: true
  95394. });
  95395. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  95396. /**
  95397. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95398. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  95399. * Recommended to be keep at 1.0 except for special cases.
  95400. */
  95401. get: function () {
  95402. return this._fovMultiplier;
  95403. },
  95404. set: function (value) {
  95405. if (isNaN(value)) {
  95406. value = 1.0;
  95407. }
  95408. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  95409. },
  95410. enumerable: true,
  95411. configurable: true
  95412. });
  95413. /**
  95414. * Attaches a new image processing configuration to the PBR Material.
  95415. * @param configuration (if null the scene configuration will be use)
  95416. */
  95417. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  95418. var _this = this;
  95419. if (configuration === this._imageProcessingConfiguration) {
  95420. return;
  95421. }
  95422. // Detaches observer.
  95423. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95424. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95425. }
  95426. // Pick the scene configuration if needed.
  95427. if (!configuration) {
  95428. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  95429. }
  95430. else {
  95431. this._imageProcessingConfiguration = configuration;
  95432. }
  95433. // Attaches observer.
  95434. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  95435. _this._computePrimaryColorFromPerceptualColor();
  95436. _this._markAllSubMeshesAsImageProcessingDirty();
  95437. });
  95438. };
  95439. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  95440. /**
  95441. * Gets the image processing configuration used either in this material.
  95442. */
  95443. get: function () {
  95444. return this._imageProcessingConfiguration;
  95445. },
  95446. /**
  95447. * Sets the Default image processing configuration used either in the this material.
  95448. *
  95449. * If sets to null, the scene one is in use.
  95450. */
  95451. set: function (value) {
  95452. this._attachImageProcessingConfiguration(value);
  95453. // Ensure the effect will be rebuilt.
  95454. this._markAllSubMeshesAsTexturesDirty();
  95455. },
  95456. enumerable: true,
  95457. configurable: true
  95458. });
  95459. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  95460. /**
  95461. * Gets wether the color curves effect is enabled.
  95462. */
  95463. get: function () {
  95464. return this.imageProcessingConfiguration.colorCurvesEnabled;
  95465. },
  95466. /**
  95467. * Sets wether the color curves effect is enabled.
  95468. */
  95469. set: function (value) {
  95470. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  95471. },
  95472. enumerable: true,
  95473. configurable: true
  95474. });
  95475. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  95476. /**
  95477. * Gets wether the color grading effect is enabled.
  95478. */
  95479. get: function () {
  95480. return this.imageProcessingConfiguration.colorGradingEnabled;
  95481. },
  95482. /**
  95483. * Gets wether the color grading effect is enabled.
  95484. */
  95485. set: function (value) {
  95486. this.imageProcessingConfiguration.colorGradingEnabled = value;
  95487. },
  95488. enumerable: true,
  95489. configurable: true
  95490. });
  95491. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  95492. /**
  95493. * Gets wether tonemapping is enabled or not.
  95494. */
  95495. get: function () {
  95496. return this._imageProcessingConfiguration.toneMappingEnabled;
  95497. },
  95498. /**
  95499. * Sets wether tonemapping is enabled or not
  95500. */
  95501. set: function (value) {
  95502. this._imageProcessingConfiguration.toneMappingEnabled = value;
  95503. },
  95504. enumerable: true,
  95505. configurable: true
  95506. });
  95507. ;
  95508. ;
  95509. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  95510. /**
  95511. * The camera exposure used on this material.
  95512. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95513. * This corresponds to a photographic exposure.
  95514. */
  95515. get: function () {
  95516. return this._imageProcessingConfiguration.exposure;
  95517. },
  95518. /**
  95519. * The camera exposure used on this material.
  95520. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95521. * This corresponds to a photographic exposure.
  95522. */
  95523. set: function (value) {
  95524. this._imageProcessingConfiguration.exposure = value;
  95525. },
  95526. enumerable: true,
  95527. configurable: true
  95528. });
  95529. ;
  95530. ;
  95531. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  95532. /**
  95533. * Gets The camera contrast used on this material.
  95534. */
  95535. get: function () {
  95536. return this._imageProcessingConfiguration.contrast;
  95537. },
  95538. /**
  95539. * Sets The camera contrast used on this material.
  95540. */
  95541. set: function (value) {
  95542. this._imageProcessingConfiguration.contrast = value;
  95543. },
  95544. enumerable: true,
  95545. configurable: true
  95546. });
  95547. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95548. /**
  95549. * Gets the Color Grading 2D Lookup Texture.
  95550. */
  95551. get: function () {
  95552. return this._imageProcessingConfiguration.colorGradingTexture;
  95553. },
  95554. /**
  95555. * Sets the Color Grading 2D Lookup Texture.
  95556. */
  95557. set: function (value) {
  95558. this.imageProcessingConfiguration.colorGradingTexture = value;
  95559. },
  95560. enumerable: true,
  95561. configurable: true
  95562. });
  95563. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95564. /**
  95565. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95566. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95567. * 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;
  95568. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95569. */
  95570. get: function () {
  95571. return this.imageProcessingConfiguration.colorCurves;
  95572. },
  95573. /**
  95574. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95575. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95576. * 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;
  95577. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95578. */
  95579. set: function (value) {
  95580. this.imageProcessingConfiguration.colorCurves = value;
  95581. },
  95582. enumerable: true,
  95583. configurable: true
  95584. });
  95585. /**
  95586. * The entire material has been created in order to prevent overdraw.
  95587. * @returns false
  95588. */
  95589. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95590. return true;
  95591. };
  95592. /**
  95593. * The entire material has been created in order to prevent overdraw.
  95594. * @returns true if blending is enable
  95595. */
  95596. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95597. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95598. };
  95599. /**
  95600. * Checks wether the material is ready to be rendered for a given mesh.
  95601. * @param mesh The mesh to render
  95602. * @param subMesh The submesh to check against
  95603. * @param useInstances Specify wether or not the material is used with instances
  95604. * @returns true if all the dependencies are ready (Textures, Effects...)
  95605. */
  95606. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95607. var _this = this;
  95608. if (useInstances === void 0) { useInstances = false; }
  95609. if (subMesh.effect && this.isFrozen) {
  95610. if (this._wasPreviouslyReady) {
  95611. return true;
  95612. }
  95613. }
  95614. if (!subMesh._materialDefines) {
  95615. subMesh._materialDefines = new BackgroundMaterialDefines();
  95616. }
  95617. var scene = this.getScene();
  95618. var defines = subMesh._materialDefines;
  95619. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95620. if (defines._renderId === scene.getRenderId()) {
  95621. return true;
  95622. }
  95623. }
  95624. var engine = scene.getEngine();
  95625. // Lights
  95626. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95627. defines._needNormals = true;
  95628. // Textures
  95629. if (defines._areTexturesDirty) {
  95630. defines._needUVs = false;
  95631. if (scene.texturesEnabled) {
  95632. if (scene.getEngine().getCaps().textureLOD) {
  95633. defines.TEXTURELODSUPPORT = true;
  95634. }
  95635. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95636. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95637. return false;
  95638. }
  95639. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95640. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95641. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95642. defines.OPACITYFRESNEL = this._opacityFresnel;
  95643. }
  95644. else {
  95645. defines.DIFFUSE = false;
  95646. defines.DIFFUSEHASALPHA = false;
  95647. defines.GAMMADIFFUSE = false;
  95648. defines.OPACITYFRESNEL = false;
  95649. }
  95650. var reflectionTexture = this._reflectionTexture;
  95651. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95652. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95653. return false;
  95654. }
  95655. defines.REFLECTION = true;
  95656. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95657. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95658. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95659. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95660. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95661. defines.REFLECTIONBGR = this.switchToBGR;
  95662. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95663. defines.INVERTCUBICMAP = true;
  95664. }
  95665. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95666. switch (reflectionTexture.coordinatesMode) {
  95667. case BABYLON.Texture.CUBIC_MODE:
  95668. case BABYLON.Texture.INVCUBIC_MODE:
  95669. defines.REFLECTIONMAP_CUBIC = true;
  95670. break;
  95671. case BABYLON.Texture.EXPLICIT_MODE:
  95672. defines.REFLECTIONMAP_EXPLICIT = true;
  95673. break;
  95674. case BABYLON.Texture.PLANAR_MODE:
  95675. defines.REFLECTIONMAP_PLANAR = true;
  95676. break;
  95677. case BABYLON.Texture.PROJECTION_MODE:
  95678. defines.REFLECTIONMAP_PROJECTION = true;
  95679. break;
  95680. case BABYLON.Texture.SKYBOX_MODE:
  95681. defines.REFLECTIONMAP_SKYBOX = true;
  95682. break;
  95683. case BABYLON.Texture.SPHERICAL_MODE:
  95684. defines.REFLECTIONMAP_SPHERICAL = true;
  95685. break;
  95686. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95687. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95688. break;
  95689. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95690. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95691. break;
  95692. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95693. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95694. break;
  95695. }
  95696. if (this.reflectionFresnel) {
  95697. defines.REFLECTIONFRESNEL = true;
  95698. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95699. this._reflectionControls.x = this.reflectionAmount;
  95700. this._reflectionControls.y = this.reflectionReflectance0;
  95701. this._reflectionControls.z = this.reflectionReflectance90;
  95702. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95703. }
  95704. else {
  95705. defines.REFLECTIONFRESNEL = false;
  95706. defines.REFLECTIONFALLOFF = false;
  95707. }
  95708. }
  95709. else {
  95710. defines.REFLECTION = false;
  95711. defines.REFLECTIONFALLOFF = false;
  95712. defines.REFLECTIONBLUR = false;
  95713. defines.REFLECTIONMAP_3D = false;
  95714. defines.REFLECTIONMAP_SPHERICAL = false;
  95715. defines.REFLECTIONMAP_PLANAR = false;
  95716. defines.REFLECTIONMAP_CUBIC = false;
  95717. defines.REFLECTIONMAP_PROJECTION = false;
  95718. defines.REFLECTIONMAP_SKYBOX = false;
  95719. defines.REFLECTIONMAP_EXPLICIT = false;
  95720. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95721. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95722. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95723. defines.INVERTCUBICMAP = false;
  95724. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95725. defines.LODINREFLECTIONALPHA = false;
  95726. defines.GAMMAREFLECTION = false;
  95727. }
  95728. }
  95729. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95730. defines.USERGBCOLOR = this._useRGBColor;
  95731. defines.NOISE = this._enableNoise;
  95732. }
  95733. if (defines._areLightsDirty) {
  95734. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95735. }
  95736. if (defines._areImageProcessingDirty) {
  95737. if (!this._imageProcessingConfiguration.isReady()) {
  95738. return false;
  95739. }
  95740. this._imageProcessingConfiguration.prepareDefines(defines);
  95741. }
  95742. // Misc.
  95743. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95744. // Values that need to be evaluated on every frame
  95745. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95746. // Attribs
  95747. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95748. if (mesh) {
  95749. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95750. mesh.createNormals(true);
  95751. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95752. }
  95753. }
  95754. }
  95755. // Get correct effect
  95756. if (defines.isDirty) {
  95757. defines.markAsProcessed();
  95758. scene.resetCachedMaterial();
  95759. // Fallbacks
  95760. var fallbacks = new BABYLON.EffectFallbacks();
  95761. if (defines.FOG) {
  95762. fallbacks.addFallback(0, "FOG");
  95763. }
  95764. if (defines.POINTSIZE) {
  95765. fallbacks.addFallback(1, "POINTSIZE");
  95766. }
  95767. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95768. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95769. fallbacks.addCPUSkinningFallback(0, mesh);
  95770. }
  95771. //Attributes
  95772. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95773. if (defines.NORMAL) {
  95774. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95775. }
  95776. if (defines.UV1) {
  95777. attribs.push(BABYLON.VertexBuffer.UVKind);
  95778. }
  95779. if (defines.UV2) {
  95780. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95781. }
  95782. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95783. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95784. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95785. "vFogInfos", "vFogColor", "pointSize",
  95786. "vClipPlane", "mBones",
  95787. "vPrimaryColor", "vPrimaryColorShadow",
  95788. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95789. "shadowLevel", "alpha",
  95790. "vBackgroundCenter", "vReflectionControl",
  95791. "vDiffuseInfos", "diffuseMatrix",
  95792. ];
  95793. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95794. var uniformBuffers = ["Material", "Scene"];
  95795. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95796. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95797. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95798. uniformsNames: uniforms,
  95799. uniformBuffersNames: uniformBuffers,
  95800. samplers: samplers,
  95801. defines: defines,
  95802. maxSimultaneousLights: this._maxSimultaneousLights
  95803. });
  95804. var onCompiled = function (effect) {
  95805. if (_this.onCompiled) {
  95806. _this.onCompiled(effect);
  95807. }
  95808. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  95809. };
  95810. var join = defines.toString();
  95811. subMesh.setEffect(scene.getEngine().createEffect("background", {
  95812. attributes: attribs,
  95813. uniformsNames: uniforms,
  95814. uniformBuffersNames: uniformBuffers,
  95815. samplers: samplers,
  95816. defines: join,
  95817. fallbacks: fallbacks,
  95818. onCompiled: onCompiled,
  95819. onError: this.onError,
  95820. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  95821. }, engine), defines);
  95822. this.buildUniformLayout();
  95823. }
  95824. if (!subMesh.effect || !subMesh.effect.isReady()) {
  95825. return false;
  95826. }
  95827. defines._renderId = scene.getRenderId();
  95828. this._wasPreviouslyReady = true;
  95829. return true;
  95830. };
  95831. /**
  95832. * Compute the primary color according to the chosen perceptual color.
  95833. */
  95834. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  95835. if (!this.__perceptualColor) {
  95836. return;
  95837. }
  95838. this._primaryColor.copyFrom(this.__perceptualColor);
  95839. // Revert gamma space.
  95840. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  95841. // Revert image processing configuration.
  95842. if (this._imageProcessingConfiguration) {
  95843. // Revert Exposure.
  95844. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  95845. }
  95846. this._computePrimaryColors();
  95847. };
  95848. /**
  95849. * Compute the highlights and shadow colors according to their chosen levels.
  95850. */
  95851. BackgroundMaterial.prototype._computePrimaryColors = function () {
  95852. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  95853. return;
  95854. }
  95855. // Find the highlight color based on the configuration.
  95856. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  95857. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  95858. // Find the shadow color based on the configuration.
  95859. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  95860. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  95861. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  95862. };
  95863. /**
  95864. * Build the uniform buffer used in the material.
  95865. */
  95866. BackgroundMaterial.prototype.buildUniformLayout = function () {
  95867. // Order is important !
  95868. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  95869. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  95870. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  95871. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  95872. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  95873. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  95874. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  95875. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  95876. this._uniformBuffer.addUniform("pointSize", 1);
  95877. this._uniformBuffer.addUniform("shadowLevel", 1);
  95878. this._uniformBuffer.addUniform("alpha", 1);
  95879. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  95880. this._uniformBuffer.addUniform("vReflectionControl", 4);
  95881. this._uniformBuffer.create();
  95882. };
  95883. /**
  95884. * Unbind the material.
  95885. */
  95886. BackgroundMaterial.prototype.unbind = function () {
  95887. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  95888. this._uniformBuffer.setTexture("diffuseSampler", null);
  95889. }
  95890. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  95891. this._uniformBuffer.setTexture("reflectionSampler", null);
  95892. }
  95893. _super.prototype.unbind.call(this);
  95894. };
  95895. /**
  95896. * Bind only the world matrix to the material.
  95897. * @param world The world matrix to bind.
  95898. */
  95899. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  95900. this._activeEffect.setMatrix("world", world);
  95901. };
  95902. /**
  95903. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  95904. * @param world The world matrix to bind.
  95905. * @param subMesh The submesh to bind for.
  95906. */
  95907. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  95908. var scene = this.getScene();
  95909. var defines = subMesh._materialDefines;
  95910. if (!defines) {
  95911. return;
  95912. }
  95913. var effect = subMesh.effect;
  95914. if (!effect) {
  95915. return;
  95916. }
  95917. this._activeEffect = effect;
  95918. // Matrices
  95919. this.bindOnlyWorldMatrix(world);
  95920. // Bones
  95921. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  95922. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  95923. if (mustRebind) {
  95924. this._uniformBuffer.bindToEffect(effect, "Material");
  95925. this.bindViewProjection(effect);
  95926. var reflectionTexture = this._reflectionTexture;
  95927. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  95928. // Texture uniforms
  95929. if (scene.texturesEnabled) {
  95930. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95931. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  95932. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  95933. }
  95934. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95935. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  95936. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  95937. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  95938. }
  95939. }
  95940. if (this.shadowLevel > 0) {
  95941. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  95942. }
  95943. this._uniformBuffer.updateFloat("alpha", this.alpha);
  95944. // Point size
  95945. if (this.pointsCloud) {
  95946. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  95947. }
  95948. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  95949. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  95950. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  95951. }
  95952. else {
  95953. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  95954. }
  95955. }
  95956. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  95957. // Textures
  95958. if (scene.texturesEnabled) {
  95959. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95960. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  95961. }
  95962. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95963. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  95964. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95965. }
  95966. else if (!defines.REFLECTIONBLUR) {
  95967. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  95968. }
  95969. else {
  95970. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  95971. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  95972. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  95973. }
  95974. if (defines.REFLECTIONFRESNEL) {
  95975. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  95976. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  95977. }
  95978. }
  95979. }
  95980. // Clip plane
  95981. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  95982. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  95983. }
  95984. if (mustRebind || !this.isFrozen) {
  95985. if (scene.lightsEnabled) {
  95986. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  95987. }
  95988. // View
  95989. this.bindView(effect);
  95990. // Fog
  95991. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  95992. // image processing
  95993. this._imageProcessingConfiguration.bind(this._activeEffect);
  95994. }
  95995. this._uniformBuffer.update();
  95996. this._afterBind(mesh);
  95997. };
  95998. /**
  95999. * Dispose the material.
  96000. * @param forceDisposeEffect Force disposal of the associated effect.
  96001. * @param forceDisposeTextures Force disposal of the associated textures.
  96002. */
  96003. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96004. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96005. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96006. if (forceDisposeTextures) {
  96007. if (this.diffuseTexture) {
  96008. this.diffuseTexture.dispose();
  96009. }
  96010. if (this.reflectionTexture) {
  96011. this.reflectionTexture.dispose();
  96012. }
  96013. }
  96014. this._renderTargets.dispose();
  96015. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96016. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96017. }
  96018. _super.prototype.dispose.call(this, forceDisposeEffect);
  96019. };
  96020. /**
  96021. * Clones the material.
  96022. * @param name The cloned name.
  96023. * @returns The cloned material.
  96024. */
  96025. BackgroundMaterial.prototype.clone = function (name) {
  96026. var _this = this;
  96027. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96028. };
  96029. /**
  96030. * Serializes the current material to its JSON representation.
  96031. * @returns The JSON representation.
  96032. */
  96033. BackgroundMaterial.prototype.serialize = function () {
  96034. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96035. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96036. return serializationObject;
  96037. };
  96038. /**
  96039. * Gets the class name of the material
  96040. * @returns "BackgroundMaterial"
  96041. */
  96042. BackgroundMaterial.prototype.getClassName = function () {
  96043. return "BackgroundMaterial";
  96044. };
  96045. /**
  96046. * Parse a JSON input to create back a background material.
  96047. * @param source The JSON data to parse
  96048. * @param scene The scene to create the parsed material in
  96049. * @param rootUrl The root url of the assets the material depends upon
  96050. * @returns the instantiated BackgroundMaterial.
  96051. */
  96052. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96053. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96054. };
  96055. /**
  96056. * Standard reflectance value at parallel view angle.
  96057. */
  96058. BackgroundMaterial.StandardReflectance0 = 0.05;
  96059. /**
  96060. * Standard reflectance value at grazing angle.
  96061. */
  96062. BackgroundMaterial.StandardReflectance90 = 0.5;
  96063. __decorate([
  96064. BABYLON.serializeAsColor3()
  96065. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96066. __decorate([
  96067. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96068. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96069. __decorate([
  96070. BABYLON.serializeAsColor3()
  96071. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96072. __decorate([
  96073. BABYLON.serialize()
  96074. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96075. __decorate([
  96076. BABYLON.serialize()
  96077. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96078. __decorate([
  96079. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96080. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96081. __decorate([
  96082. BABYLON.serializeAsTexture()
  96083. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96084. __decorate([
  96085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96086. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96087. __decorate([
  96088. BABYLON.serialize()
  96089. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96090. __decorate([
  96091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96092. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96093. __decorate([
  96094. BABYLON.serializeAsTexture()
  96095. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96096. __decorate([
  96097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96098. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96099. __decorate([
  96100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96101. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96102. __decorate([
  96103. BABYLON.serialize()
  96104. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96105. __decorate([
  96106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96107. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96108. __decorate([
  96109. BABYLON.serializeAsVector3()
  96110. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96111. __decorate([
  96112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96113. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96114. __decorate([
  96115. BABYLON.serialize()
  96116. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96117. __decorate([
  96118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96119. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96120. __decorate([
  96121. BABYLON.serialize()
  96122. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96123. __decorate([
  96124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96125. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96126. __decorate([
  96127. BABYLON.serialize()
  96128. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96129. __decorate([
  96130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96131. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96132. __decorate([
  96133. BABYLON.serialize()
  96134. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96135. __decorate([
  96136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96137. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96138. __decorate([
  96139. BABYLON.serialize()
  96140. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96141. __decorate([
  96142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96143. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96144. __decorate([
  96145. BABYLON.serialize()
  96146. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96147. __decorate([
  96148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96149. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96150. __decorate([
  96151. BABYLON.serialize()
  96152. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96153. __decorate([
  96154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96155. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96156. __decorate([
  96157. BABYLON.serialize()
  96158. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96159. __decorate([
  96160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96161. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96162. __decorate([
  96163. BABYLON.serialize()
  96164. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96165. __decorate([
  96166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96167. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96168. __decorate([
  96169. BABYLON.serializeAsImageProcessingConfiguration()
  96170. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96171. return BackgroundMaterial;
  96172. }(BABYLON.PushMaterial));
  96173. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96174. })(BABYLON || (BABYLON = {}));
  96175. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96176. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96177. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96178. s = arguments[i];
  96179. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96180. t[p] = s[p];
  96181. }
  96182. return t;
  96183. };
  96184. var BABYLON;
  96185. (function (BABYLON) {
  96186. /**
  96187. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96188. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96189. * It also helps with the default setup of your imageProcessing configuration.
  96190. */
  96191. var EnvironmentHelper = /** @class */ (function () {
  96192. /**
  96193. * constructor
  96194. * @param options
  96195. * @param scene The scene to add the material to
  96196. */
  96197. function EnvironmentHelper(options, scene) {
  96198. var _this = this;
  96199. this._errorHandler = function (message, exception) {
  96200. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96201. };
  96202. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96203. this._scene = scene;
  96204. this.onErrorObservable = new BABYLON.Observable();
  96205. this._setupBackground();
  96206. this._setupImageProcessing();
  96207. }
  96208. /**
  96209. * Creates the default options for the helper.
  96210. */
  96211. EnvironmentHelper._getDefaultOptions = function () {
  96212. return {
  96213. createGround: true,
  96214. groundSize: 15,
  96215. groundTexture: this._groundTextureCDNUrl,
  96216. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96217. groundOpacity: 0.9,
  96218. enableGroundShadow: true,
  96219. groundShadowLevel: 0.5,
  96220. enableGroundMirror: false,
  96221. groundMirrorSizeRatio: 0.3,
  96222. groundMirrorBlurKernel: 64,
  96223. groundMirrorAmount: 1,
  96224. groundMirrorFresnelWeight: 1,
  96225. groundMirrorFallOffDistance: 0,
  96226. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96227. groundYBias: 0.00001,
  96228. createSkybox: true,
  96229. skyboxSize: 20,
  96230. skyboxTexture: this._skyboxTextureCDNUrl,
  96231. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96232. backgroundYRotation: 0,
  96233. sizeAuto: true,
  96234. rootPosition: BABYLON.Vector3.Zero(),
  96235. setupImageProcessing: true,
  96236. environmentTexture: this._environmentTextureCDNUrl,
  96237. cameraExposure: 0.8,
  96238. cameraContrast: 1.2,
  96239. toneMappingEnabled: true,
  96240. };
  96241. };
  96242. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96243. /**
  96244. * Gets the root mesh created by the helper.
  96245. */
  96246. get: function () {
  96247. return this._rootMesh;
  96248. },
  96249. enumerable: true,
  96250. configurable: true
  96251. });
  96252. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96253. /**
  96254. * Gets the skybox created by the helper.
  96255. */
  96256. get: function () {
  96257. return this._skybox;
  96258. },
  96259. enumerable: true,
  96260. configurable: true
  96261. });
  96262. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96263. /**
  96264. * Gets the skybox texture created by the helper.
  96265. */
  96266. get: function () {
  96267. return this._skyboxTexture;
  96268. },
  96269. enumerable: true,
  96270. configurable: true
  96271. });
  96272. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96273. /**
  96274. * Gets the skybox material created by the helper.
  96275. */
  96276. get: function () {
  96277. return this._skyboxMaterial;
  96278. },
  96279. enumerable: true,
  96280. configurable: true
  96281. });
  96282. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96283. /**
  96284. * Gets the ground mesh created by the helper.
  96285. */
  96286. get: function () {
  96287. return this._ground;
  96288. },
  96289. enumerable: true,
  96290. configurable: true
  96291. });
  96292. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96293. /**
  96294. * Gets the ground texture created by the helper.
  96295. */
  96296. get: function () {
  96297. return this._groundTexture;
  96298. },
  96299. enumerable: true,
  96300. configurable: true
  96301. });
  96302. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96303. /**
  96304. * Gets the ground mirror created by the helper.
  96305. */
  96306. get: function () {
  96307. return this._groundMirror;
  96308. },
  96309. enumerable: true,
  96310. configurable: true
  96311. });
  96312. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96313. /**
  96314. * Gets the ground mirror render list to helps pushing the meshes
  96315. * you wish in the ground reflection.
  96316. */
  96317. get: function () {
  96318. if (this._groundMirror) {
  96319. return this._groundMirror.renderList;
  96320. }
  96321. return null;
  96322. },
  96323. enumerable: true,
  96324. configurable: true
  96325. });
  96326. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  96327. /**
  96328. * Gets the ground material created by the helper.
  96329. */
  96330. get: function () {
  96331. return this._groundMaterial;
  96332. },
  96333. enumerable: true,
  96334. configurable: true
  96335. });
  96336. /**
  96337. * Updates the background according to the new options
  96338. * @param options
  96339. */
  96340. EnvironmentHelper.prototype.updateOptions = function (options) {
  96341. var newOptions = __assign({}, this._options, options);
  96342. if (this._ground && !newOptions.createGround) {
  96343. this._ground.dispose();
  96344. this._ground = null;
  96345. }
  96346. if (this._groundMaterial && !newOptions.createGround) {
  96347. this._groundMaterial.dispose();
  96348. this._groundMaterial = null;
  96349. }
  96350. if (this._groundTexture) {
  96351. if (this._options.groundTexture != newOptions.groundTexture) {
  96352. this._groundTexture.dispose();
  96353. this._groundTexture = null;
  96354. }
  96355. }
  96356. if (this._skybox && !newOptions.createSkybox) {
  96357. this._skybox.dispose();
  96358. this._skybox = null;
  96359. }
  96360. if (this._skyboxMaterial && !newOptions.createSkybox) {
  96361. this._skyboxMaterial.dispose();
  96362. this._skyboxMaterial = null;
  96363. }
  96364. if (this._skyboxTexture) {
  96365. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  96366. this._skyboxTexture.dispose();
  96367. this._skyboxTexture = null;
  96368. }
  96369. }
  96370. if (this._groundMirror && !newOptions.enableGroundMirror) {
  96371. this._groundMirror.dispose();
  96372. this._groundMirror = null;
  96373. }
  96374. if (this._scene.environmentTexture) {
  96375. if (this._options.environmentTexture != newOptions.environmentTexture) {
  96376. this._scene.environmentTexture.dispose();
  96377. }
  96378. }
  96379. this._options = newOptions;
  96380. this._setupBackground();
  96381. this._setupImageProcessing();
  96382. };
  96383. /**
  96384. * Sets the primary color of all the available elements.
  96385. * @param color the main color to affect to the ground and the background
  96386. */
  96387. EnvironmentHelper.prototype.setMainColor = function (color) {
  96388. if (this.groundMaterial) {
  96389. this.groundMaterial.primaryColor = color;
  96390. }
  96391. if (this.skyboxMaterial) {
  96392. this.skyboxMaterial.primaryColor = color;
  96393. }
  96394. if (this.groundMirror) {
  96395. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  96396. }
  96397. };
  96398. /**
  96399. * Setup the image processing according to the specified options.
  96400. */
  96401. EnvironmentHelper.prototype._setupImageProcessing = function () {
  96402. if (this._options.setupImageProcessing) {
  96403. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  96404. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  96405. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  96406. this._setupEnvironmentTexture();
  96407. }
  96408. };
  96409. /**
  96410. * Setup the environment texture according to the specified options.
  96411. */
  96412. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  96413. if (this._scene.environmentTexture) {
  96414. return;
  96415. }
  96416. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  96417. this._scene.environmentTexture = this._options.environmentTexture;
  96418. return;
  96419. }
  96420. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  96421. this._scene.environmentTexture = environmentTexture;
  96422. };
  96423. /**
  96424. * Setup the background according to the specified options.
  96425. */
  96426. EnvironmentHelper.prototype._setupBackground = function () {
  96427. if (!this._rootMesh) {
  96428. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  96429. }
  96430. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  96431. var sceneSize = this._getSceneSize();
  96432. if (this._options.createGround) {
  96433. this._setupGround(sceneSize);
  96434. this._setupGroundMaterial();
  96435. this._setupGroundDiffuseTexture();
  96436. if (this._options.enableGroundMirror) {
  96437. this._setupGroundMirrorTexture(sceneSize);
  96438. }
  96439. this._setupMirrorInGroundMaterial();
  96440. }
  96441. if (this._options.createSkybox) {
  96442. this._setupSkybox(sceneSize);
  96443. this._setupSkyboxMaterial();
  96444. this._setupSkyboxReflectionTexture();
  96445. }
  96446. this._rootMesh.position.x = sceneSize.rootPosition.x;
  96447. this._rootMesh.position.z = sceneSize.rootPosition.z;
  96448. this._rootMesh.position.y = sceneSize.rootPosition.y;
  96449. };
  96450. /**
  96451. * Get the scene sizes according to the setup.
  96452. */
  96453. EnvironmentHelper.prototype._getSceneSize = function () {
  96454. var _this = this;
  96455. var groundSize = this._options.groundSize;
  96456. var skyboxSize = this._options.skyboxSize;
  96457. var rootPosition = this._options.rootPosition;
  96458. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  96459. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96460. }
  96461. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  96462. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  96463. });
  96464. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  96465. if (this._options.sizeAuto) {
  96466. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  96467. this._scene.activeCamera.upperRadiusLimit) {
  96468. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  96469. skyboxSize = groundSize;
  96470. }
  96471. var sceneDiagonalLenght = sceneDiagonal.length();
  96472. if (sceneDiagonalLenght > groundSize) {
  96473. groundSize = sceneDiagonalLenght * 2;
  96474. skyboxSize = groundSize;
  96475. }
  96476. // 10 % bigger.
  96477. groundSize *= 1.1;
  96478. skyboxSize *= 1.5;
  96479. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  96480. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  96481. }
  96482. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96483. };
  96484. /**
  96485. * Setup the ground according to the specified options.
  96486. */
  96487. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  96488. var _this = this;
  96489. if (!this._ground) {
  96490. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  96491. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  96492. this._ground.parent = this._rootMesh;
  96493. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96494. }
  96495. this._ground.receiveShadows = this._options.enableGroundShadow;
  96496. };
  96497. /**
  96498. * Setup the ground material according to the specified options.
  96499. */
  96500. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96501. if (!this._groundMaterial) {
  96502. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96503. }
  96504. this._groundMaterial.alpha = this._options.groundOpacity;
  96505. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96506. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96507. this._groundMaterial.primaryColor = this._options.groundColor;
  96508. this._groundMaterial.useRGBColor = false;
  96509. this._groundMaterial.enableNoise = true;
  96510. if (this._ground) {
  96511. this._ground.material = this._groundMaterial;
  96512. }
  96513. };
  96514. /**
  96515. * Setup the ground diffuse texture according to the specified options.
  96516. */
  96517. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96518. if (!this._groundMaterial) {
  96519. return;
  96520. }
  96521. if (this._groundTexture) {
  96522. return;
  96523. }
  96524. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96525. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96526. return;
  96527. }
  96528. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96529. diffuseTexture.gammaSpace = false;
  96530. diffuseTexture.hasAlpha = true;
  96531. this._groundMaterial.diffuseTexture = diffuseTexture;
  96532. };
  96533. /**
  96534. * Setup the ground mirror texture according to the specified options.
  96535. */
  96536. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96537. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96538. if (!this._groundMirror) {
  96539. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96540. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96541. this._groundMirror.anisotropicFilteringLevel = 1;
  96542. this._groundMirror.wrapU = wrapping;
  96543. this._groundMirror.wrapV = wrapping;
  96544. this._groundMirror.gammaSpace = false;
  96545. if (this._groundMirror.renderList) {
  96546. for (var i = 0; i < this._scene.meshes.length; i++) {
  96547. var mesh = this._scene.meshes[i];
  96548. if (mesh !== this._ground &&
  96549. mesh !== this._skybox &&
  96550. mesh !== this._rootMesh) {
  96551. this._groundMirror.renderList.push(mesh);
  96552. }
  96553. }
  96554. }
  96555. }
  96556. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96557. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96558. };
  96559. /**
  96560. * Setup the ground to receive the mirror texture.
  96561. */
  96562. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96563. if (this._groundMaterial) {
  96564. this._groundMaterial.reflectionTexture = this._groundMirror;
  96565. this._groundMaterial.reflectionFresnel = true;
  96566. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96567. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96568. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96569. }
  96570. };
  96571. /**
  96572. * Setup the skybox according to the specified options.
  96573. */
  96574. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96575. var _this = this;
  96576. if (!this._skybox) {
  96577. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96578. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96579. }
  96580. this._skybox.parent = this._rootMesh;
  96581. };
  96582. /**
  96583. * Setup the skybox material according to the specified options.
  96584. */
  96585. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96586. if (!this._skybox) {
  96587. return;
  96588. }
  96589. if (!this._skyboxMaterial) {
  96590. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96591. }
  96592. this._skyboxMaterial.useRGBColor = false;
  96593. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96594. this._skyboxMaterial.enableNoise = true;
  96595. this._skybox.material = this._skyboxMaterial;
  96596. };
  96597. /**
  96598. * Setup the skybox reflection texture according to the specified options.
  96599. */
  96600. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96601. if (!this._skyboxMaterial) {
  96602. return;
  96603. }
  96604. if (this._skyboxTexture) {
  96605. return;
  96606. }
  96607. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96608. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  96609. return;
  96610. }
  96611. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96612. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96613. this._skyboxTexture.gammaSpace = false;
  96614. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96615. };
  96616. /**
  96617. * Dispose all the elements created by the Helper.
  96618. */
  96619. EnvironmentHelper.prototype.dispose = function () {
  96620. if (this._groundMaterial) {
  96621. this._groundMaterial.dispose(true, true);
  96622. }
  96623. if (this._skyboxMaterial) {
  96624. this._skyboxMaterial.dispose(true, true);
  96625. }
  96626. this._rootMesh.dispose(false);
  96627. };
  96628. /**
  96629. * Default ground texture URL.
  96630. */
  96631. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96632. /**
  96633. * Default skybox texture URL.
  96634. */
  96635. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96636. /**
  96637. * Default environment texture URL.
  96638. */
  96639. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96640. return EnvironmentHelper;
  96641. }());
  96642. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96643. })(BABYLON || (BABYLON = {}));
  96644. //# sourceMappingURL=babylon.environmentHelper.js.map
  96645. var BABYLON;
  96646. (function (BABYLON) {
  96647. /**
  96648. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96649. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96650. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96651. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96652. */
  96653. var VideoDome = /** @class */ (function (_super) {
  96654. __extends(VideoDome, _super);
  96655. /**
  96656. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96657. * @param name Element's name, child elements will append suffixes for their own names.
  96658. * @param urlsOrVideo
  96659. * @param options An object containing optional or exposed sub element properties:
  96660. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96661. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96662. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96663. * @param options **loop=true** Automatically loop video on end.
  96664. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96665. */
  96666. function VideoDome(name, urlsOrVideo, options, scene) {
  96667. var _this = _super.call(this, name, scene) || this;
  96668. // set defaults and manage values
  96669. name = name || "videoDome";
  96670. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96671. options.clickToPlay = Boolean(options.clickToPlay);
  96672. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96673. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96674. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96675. // create
  96676. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96677. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96678. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96679. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96680. flat: false,
  96681. radius: options.size,
  96682. subdivisions: options.resolution,
  96683. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96684. }, scene);
  96685. // configure material
  96686. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96687. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96688. material.reflectionTexture = _this._videoTexture;
  96689. material.useEquirectangularFOV = true;
  96690. material.fovMultiplier = 1.0;
  96691. // configure mesh
  96692. _this._mesh.material = material;
  96693. _this._mesh.parent = _this;
  96694. // optional configuration
  96695. if (options.clickToPlay) {
  96696. scene.onPointerUp = function () {
  96697. _this._videoTexture.video.play();
  96698. };
  96699. }
  96700. return _this;
  96701. }
  96702. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96703. /**
  96704. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96705. * Also see the options.resolution property.
  96706. */
  96707. get: function () {
  96708. return this._material.fovMultiplier;
  96709. },
  96710. set: function (value) {
  96711. this._material.fovMultiplier = value;
  96712. },
  96713. enumerable: true,
  96714. configurable: true
  96715. });
  96716. /**
  96717. * Releases resources associated with this node.
  96718. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96719. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96720. */
  96721. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96722. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96723. this._videoTexture.dispose();
  96724. this._mesh.dispose();
  96725. this._material.dispose();
  96726. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96727. };
  96728. return VideoDome;
  96729. }(BABYLON.Node));
  96730. BABYLON.VideoDome = VideoDome;
  96731. })(BABYLON || (BABYLON = {}));
  96732. //# sourceMappingURL=babylon.videoDome.js.map
  96733. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(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"};
  96734. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 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}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  96735. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  96736. globalObject["BABYLON"] = BABYLON;
  96737. //backwards compatibility
  96738. if(typeof earcut !== 'undefined') {
  96739. globalObject["Earcut"] = {
  96740. earcut: earcut
  96741. };
  96742. }
  96743. return BABYLON;
  96744. });
  96745. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(19)))
  96746. /***/ }),
  96747. /* 1 */
  96748. /***/ (function(module, exports, __webpack_require__) {
  96749. "use strict";
  96750. Object.defineProperty(exports, "__esModule", { value: true });
  96751. var babylonjs_1 = __webpack_require__(0);
  96752. var helper_1 = __webpack_require__(3);
  96753. /**
  96754. * This is a simple HTML mapper.
  96755. * This mapper parses a single HTML element and returns the configuration from its attributes.
  96756. * it parses numbers and boolean values to the corresponding variable types.
  96757. * The following HTML element:
  96758. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  96759. *
  96760. * {
  96761. * test: 1, //a number!
  96762. * randomFlag: boolean, //camelCase and boolean
  96763. * a: {
  96764. * string: {
  96765. * object: "test" //dot-separated object levels
  96766. * }
  96767. * }
  96768. * }
  96769. */
  96770. var HTMLMapper = /** @class */ (function () {
  96771. function HTMLMapper() {
  96772. }
  96773. /**
  96774. * Map a specific element and get configuration from it
  96775. * @param element the HTML element to analyze.
  96776. */
  96777. HTMLMapper.prototype.map = function (element) {
  96778. var config = {};
  96779. var _loop_1 = function (attrIdx) {
  96780. var attr = element.attributes.item(attrIdx);
  96781. if (!attr) {
  96782. return "continue";
  96783. }
  96784. // map "object.property" to the right configuration place.
  96785. var split = attr.nodeName.split('.');
  96786. split.reduce(function (currentConfig, key, idx) {
  96787. //convert html-style to json-style
  96788. var camelKey = helper_1.kebabToCamel(key);
  96789. if (idx === split.length - 1) {
  96790. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  96791. if (val === "true") {
  96792. val = true;
  96793. }
  96794. else if (val === "false") {
  96795. val = false;
  96796. }
  96797. else {
  96798. var isnum = /^\d+$/.test(val);
  96799. if (isnum) {
  96800. var number = parseFloat(val);
  96801. if (!isNaN(number)) {
  96802. val = number;
  96803. }
  96804. }
  96805. }
  96806. currentConfig[camelKey] = val;
  96807. }
  96808. else {
  96809. currentConfig[camelKey] = currentConfig[camelKey] || {};
  96810. }
  96811. return currentConfig[camelKey];
  96812. }, config);
  96813. };
  96814. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  96815. _loop_1(attrIdx);
  96816. }
  96817. return config;
  96818. };
  96819. return HTMLMapper;
  96820. }());
  96821. /**
  96822. * A simple string-to-JSON mapper.
  96823. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  96824. */
  96825. var JSONMapper = /** @class */ (function () {
  96826. function JSONMapper() {
  96827. }
  96828. JSONMapper.prototype.map = function (rawSource) {
  96829. return JSON.parse(rawSource);
  96830. };
  96831. return JSONMapper;
  96832. }());
  96833. /**
  96834. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  96835. * DOM elements and attributes.
  96836. */
  96837. var DOMMapper = /** @class */ (function () {
  96838. function DOMMapper() {
  96839. }
  96840. /**
  96841. * The mapping function that will convert HTML data to a viewer configuration object
  96842. * @param baseElement the baseElement from which to start traversing
  96843. * @returns a ViewerCOnfiguration object from the provided HTML Element
  96844. */
  96845. DOMMapper.prototype.map = function (baseElement) {
  96846. var htmlMapper = new HTMLMapper();
  96847. var config = htmlMapper.map(baseElement);
  96848. var traverseChildren = function (element, partConfig) {
  96849. var children = element.children;
  96850. if (children.length) {
  96851. for (var i = 0; i < children.length; ++i) {
  96852. var item = children.item(i);
  96853. // use the HTML Mapper to read configuration from a single element
  96854. var configMapped = htmlMapper.map(item);
  96855. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  96856. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  96857. partConfig[key] = [];
  96858. }
  96859. else {
  96860. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  96861. partConfig.push(configMapped);
  96862. }
  96863. else if (partConfig[key]) {
  96864. //exists already! probably an array
  96865. element.setAttribute('array', 'true');
  96866. var oldItem = partConfig[key];
  96867. partConfig = [oldItem, configMapped];
  96868. }
  96869. else {
  96870. partConfig[key] = configMapped;
  96871. }
  96872. }
  96873. traverseChildren(item, partConfig[key] || configMapped);
  96874. }
  96875. }
  96876. return partConfig;
  96877. };
  96878. traverseChildren(baseElement, config);
  96879. return config;
  96880. };
  96881. return DOMMapper;
  96882. }());
  96883. /**
  96884. * The MapperManager manages the different implemented mappers.
  96885. * It allows the user to register new mappers as well and use them to parse their own configuration data
  96886. */
  96887. var MapperManager = /** @class */ (function () {
  96888. function MapperManager() {
  96889. this._mappers = {
  96890. "html": new HTMLMapper(),
  96891. "json": new JSONMapper(),
  96892. "dom": new DOMMapper()
  96893. };
  96894. }
  96895. /**
  96896. * Get a specific configuration mapper.
  96897. *
  96898. * @param type the name of the mapper to load
  96899. */
  96900. MapperManager.prototype.getMapper = function (type) {
  96901. if (!this._mappers[type]) {
  96902. babylonjs_1.Tools.Error("No mapper defined for " + type);
  96903. }
  96904. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  96905. };
  96906. /**
  96907. * Use this functio to register your own configuration mapper.
  96908. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  96909. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  96910. * @param mapper The implemented mapper
  96911. */
  96912. MapperManager.prototype.registerMapper = function (type, mapper) {
  96913. this._mappers[type] = mapper;
  96914. };
  96915. /**
  96916. * Dispose the mapper manager and all of its mappers.
  96917. */
  96918. MapperManager.prototype.dispose = function () {
  96919. this._mappers = {};
  96920. };
  96921. /**
  96922. * The default mapper is the JSON mapper.
  96923. */
  96924. MapperManager.DefaultMapper = 'json';
  96925. return MapperManager;
  96926. }());
  96927. exports.MapperManager = MapperManager;
  96928. /**
  96929. * mapperManager is a singleton of the type MapperManager.
  96930. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  96931. * or indirectly with using BabylonViewer.disposeAll()
  96932. */
  96933. exports.mapperManager = new MapperManager();
  96934. /***/ }),
  96935. /* 2 */
  96936. /***/ (function(module, exports, __webpack_require__) {
  96937. (function (global, factory) {
  96938. true ? module.exports = factory() :
  96939. typeof define === 'function' && define.amd ? define(factory) :
  96940. (global.deepmerge = factory());
  96941. }(this, (function () { 'use strict';
  96942. var isMergeableObject = function isMergeableObject(value) {
  96943. return isNonNullObject(value)
  96944. && !isSpecial(value)
  96945. };
  96946. function isNonNullObject(value) {
  96947. return !!value && typeof value === 'object'
  96948. }
  96949. function isSpecial(value) {
  96950. var stringValue = Object.prototype.toString.call(value);
  96951. return stringValue === '[object RegExp]'
  96952. || stringValue === '[object Date]'
  96953. || isReactElement(value)
  96954. }
  96955. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  96956. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  96957. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  96958. function isReactElement(value) {
  96959. return value.$$typeof === REACT_ELEMENT_TYPE
  96960. }
  96961. function emptyTarget(val) {
  96962. return Array.isArray(val) ? [] : {}
  96963. }
  96964. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  96965. var clone = !optionsArgument || optionsArgument.clone !== false;
  96966. return (clone && isMergeableObject(value))
  96967. ? deepmerge(emptyTarget(value), value, optionsArgument)
  96968. : value
  96969. }
  96970. function defaultArrayMerge(target, source, optionsArgument) {
  96971. return target.concat(source).map(function(element) {
  96972. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  96973. })
  96974. }
  96975. function mergeObject(target, source, optionsArgument) {
  96976. var destination = {};
  96977. if (isMergeableObject(target)) {
  96978. Object.keys(target).forEach(function(key) {
  96979. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  96980. });
  96981. }
  96982. Object.keys(source).forEach(function(key) {
  96983. if (!isMergeableObject(source[key]) || !target[key]) {
  96984. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  96985. } else {
  96986. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  96987. }
  96988. });
  96989. return destination
  96990. }
  96991. function deepmerge(target, source, optionsArgument) {
  96992. var sourceIsArray = Array.isArray(source);
  96993. var targetIsArray = Array.isArray(target);
  96994. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  96995. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  96996. if (!sourceAndTargetTypesMatch) {
  96997. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  96998. } else if (sourceIsArray) {
  96999. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97000. return arrayMerge(target, source, optionsArgument)
  97001. } else {
  97002. return mergeObject(target, source, optionsArgument)
  97003. }
  97004. }
  97005. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97006. if (!Array.isArray(array)) {
  97007. throw new Error('first argument should be an array')
  97008. }
  97009. return array.reduce(function(prev, next) {
  97010. return deepmerge(prev, next, optionsArgument)
  97011. }, {})
  97012. };
  97013. var deepmerge_1 = deepmerge;
  97014. return deepmerge_1;
  97015. })));
  97016. /***/ }),
  97017. /* 3 */
  97018. /***/ (function(module, exports, __webpack_require__) {
  97019. "use strict";
  97020. Object.defineProperty(exports, "__esModule", { value: true });
  97021. /**
  97022. * Is the provided string a URL?
  97023. *
  97024. * @param urlToCheck the url to inspect
  97025. */
  97026. function isUrl(urlToCheck) {
  97027. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97028. return true;
  97029. }
  97030. return false;
  97031. }
  97032. exports.isUrl = isUrl;
  97033. /**
  97034. * Convert a string from kebab-case to camelCase
  97035. * @param s string to convert
  97036. */
  97037. function kebabToCamel(s) {
  97038. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97039. }
  97040. exports.kebabToCamel = kebabToCamel;
  97041. //https://gist.github.com/youssman/745578062609e8acac9f
  97042. /**
  97043. * Convert a string from camelCase to kebab-case
  97044. * @param str string to convert
  97045. */
  97046. function camelToKebab(str) {
  97047. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97048. }
  97049. exports.camelToKebab = camelToKebab;
  97050. /***/ }),
  97051. /* 4 */
  97052. /***/ (function(module, exports, __webpack_require__) {
  97053. "use strict";
  97054. Object.defineProperty(exports, "__esModule", { value: true });
  97055. var babylonjs_1 = __webpack_require__(0);
  97056. /**
  97057. * The viewer manager is the container for all viewers currently registered on this page.
  97058. * It is possible to have more than one viewer on a single page.
  97059. */
  97060. var ViewerManager = /** @class */ (function () {
  97061. function ViewerManager() {
  97062. this._viewers = {};
  97063. this.onViewerAddedObservable = new babylonjs_1.Observable();
  97064. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  97065. }
  97066. /**
  97067. * Adding a new viewer to the viewer manager and start tracking it.
  97068. * @param viewer the viewer to add
  97069. */
  97070. ViewerManager.prototype.addViewer = function (viewer) {
  97071. this._viewers[viewer.getBaseId()] = viewer;
  97072. this._onViewerAdded(viewer);
  97073. };
  97074. /**
  97075. * remove a viewer from the viewer manager
  97076. * @param viewer the viewer to remove
  97077. */
  97078. ViewerManager.prototype.removeViewer = function (viewer) {
  97079. var id = viewer.getBaseId();
  97080. delete this._viewers[id];
  97081. this.onViewerRemovedObservable.notifyObservers(id);
  97082. };
  97083. /**
  97084. * 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)
  97085. * @param id the id of the HTMl element (or the viewer's, if none provided)
  97086. */
  97087. ViewerManager.prototype.getViewerById = function (id) {
  97088. return this._viewers[id];
  97089. };
  97090. /**
  97091. * Get a viewer using a container element
  97092. * @param element the HTML element to search viewers associated with
  97093. */
  97094. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  97095. for (var id in this._viewers) {
  97096. if (this._viewers[id].containerElement === element) {
  97097. return this.getViewerById(id);
  97098. }
  97099. }
  97100. };
  97101. /**
  97102. * Get a promise that will fullfil when this viewer was initialized.
  97103. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  97104. * you will get the viewer after everything was already configured.
  97105. * @param id the viewer id to find
  97106. */
  97107. ViewerManager.prototype.getViewerPromiseById = function (id) {
  97108. var _this = this;
  97109. return new Promise(function (resolve, reject) {
  97110. var localViewer = _this.getViewerById(id);
  97111. if (localViewer) {
  97112. return resolve(localViewer);
  97113. }
  97114. var viewerFunction = function (viewer) {
  97115. if (viewer.getBaseId() === id) {
  97116. resolve(viewer);
  97117. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  97118. }
  97119. };
  97120. _this.onViewerAddedObservable.add(viewerFunction);
  97121. });
  97122. };
  97123. ViewerManager.prototype._onViewerAdded = function (viewer) {
  97124. this.onViewerAdded && this.onViewerAdded(viewer);
  97125. this.onViewerAddedObservable.notifyObservers(viewer);
  97126. };
  97127. /**
  97128. * dispose the manager and all of its associated viewers
  97129. */
  97130. ViewerManager.prototype.dispose = function () {
  97131. for (var id in this._viewers) {
  97132. this._viewers[id].dispose();
  97133. }
  97134. };
  97135. return ViewerManager;
  97136. }());
  97137. exports.ViewerManager = ViewerManager;
  97138. exports.viewerManager = new ViewerManager();
  97139. /***/ }),
  97140. /* 5 */
  97141. /***/ (function(module, exports, __webpack_require__) {
  97142. "use strict";
  97143. var __extends = (this && this.__extends) || (function () {
  97144. var extendStatics = Object.setPrototypeOf ||
  97145. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  97146. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  97147. return function (d, b) {
  97148. extendStatics(d, b);
  97149. function __() { this.constructor = d; }
  97150. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  97151. };
  97152. })();
  97153. Object.defineProperty(exports, "__esModule", { value: true });
  97154. var viewer_1 = __webpack_require__(6);
  97155. var babylonjs_1 = __webpack_require__(0);
  97156. /**
  97157. * The Default viewer is the default implementation of the AbstractViewer.
  97158. * It uses the templating system to render a new canvas and controls.
  97159. */
  97160. var DefaultViewer = /** @class */ (function (_super) {
  97161. __extends(DefaultViewer, _super);
  97162. /**
  97163. * Create a new default viewer
  97164. * @param containerElement the element in which the templates will be rendered
  97165. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  97166. */
  97167. function DefaultViewer(containerElement, initialConfiguration) {
  97168. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  97169. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  97170. _this.containerElement = containerElement;
  97171. _this._onModelLoaded = function (model) {
  97172. _this._configureTemplate(model);
  97173. // with a short timeout, making sure everything is there already.
  97174. var hideLoadingDelay = 500;
  97175. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  97176. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  97177. }
  97178. setTimeout(function () {
  97179. _this.hideLoadingScreen();
  97180. }, hideLoadingDelay);
  97181. return;
  97182. };
  97183. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  97184. return _this;
  97185. }
  97186. /**
  97187. * Overriding the AbstractViewer's _initScene fcuntion
  97188. */
  97189. DefaultViewer.prototype._initScene = function () {
  97190. var _this = this;
  97191. return _super.prototype._initScene.call(this).then(function () {
  97192. _this._extendClassWithConfig(_this.scene, _this._configuration.scene);
  97193. return _this.scene;
  97194. });
  97195. };
  97196. /**
  97197. * This will be executed when the templates initialize.
  97198. */
  97199. DefaultViewer.prototype._onTemplatesLoaded = function () {
  97200. var _this = this;
  97201. this.showLoadingScreen();
  97202. // navbar
  97203. this._initNavbar();
  97204. // close overlay button
  97205. var closeButton = document.getElementById('close-button');
  97206. if (closeButton) {
  97207. closeButton.addEventListener('pointerdown', function () {
  97208. _this.hideOverlayScreen();
  97209. });
  97210. }
  97211. return _super.prototype._onTemplatesLoaded.call(this);
  97212. };
  97213. DefaultViewer.prototype._initNavbar = function () {
  97214. var navbar = this.templateManager.getTemplate('navBar');
  97215. if (navbar) {
  97216. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  97217. var navbarShown_1 = true;
  97218. var timeoutCancel_1 /*: number*/;
  97219. var triggerNavbar = function (show, evt) {
  97220. if (show === void 0) { show = false; }
  97221. // only left-click on no-button.
  97222. if (!navbar || evt.button > 0)
  97223. return;
  97224. // clear timeout
  97225. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  97226. // if state is the same, do nothing
  97227. if (show === navbarShown_1)
  97228. return;
  97229. //showing? simply show it!
  97230. if (show) {
  97231. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  97232. navbarShown_1 = show;
  97233. }
  97234. else {
  97235. var visibilityTimeout = 2000;
  97236. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  97237. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  97238. }
  97239. // not showing? set timeout until it is removed.
  97240. timeoutCancel_1 = setTimeout(function () {
  97241. if (navbar) {
  97242. navbar.parent.style.bottom = '-' + navbarHeight_1;
  97243. }
  97244. navbarShown_1 = show;
  97245. }, visibilityTimeout);
  97246. }
  97247. };
  97248. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  97249. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  97250. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  97251. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  97252. // other events
  97253. var viewerTemplate = this.templateManager.getTemplate('viewer');
  97254. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  97255. // full screen
  97256. var triggerFullscren = function (eventData) {
  97257. if (viewerElement_1) {
  97258. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  97259. if (!fullscreenElement) {
  97260. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  97261. requestFullScreen.call(viewerElement_1);
  97262. }
  97263. else {
  97264. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  97265. exitFullscreen.call(document);
  97266. }
  97267. }
  97268. };
  97269. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  97270. }
  97271. };
  97272. /**
  97273. * Preparing the container element to present the viewer
  97274. */
  97275. DefaultViewer.prototype._prepareContainerElement = function () {
  97276. this.containerElement.style.position = 'relative';
  97277. this.containerElement.style.display = 'flex';
  97278. };
  97279. /**
  97280. * This function will configure the templates and update them after a model was loaded
  97281. * It is mainly responsible to changing the title and subtitle etc'.
  97282. * @param model the model to be used to configure the templates by
  97283. */
  97284. DefaultViewer.prototype._configureTemplate = function (model) {
  97285. var navbar = this.templateManager.getTemplate('navBar');
  97286. if (!navbar)
  97287. return;
  97288. var modelConfiguration = model.configuration;
  97289. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  97290. if (metadataContainer) {
  97291. if (modelConfiguration.title !== undefined) {
  97292. var element = metadataContainer.querySelector('span.model-title');
  97293. if (element) {
  97294. element.innerHTML = modelConfiguration.title;
  97295. }
  97296. }
  97297. if (modelConfiguration.subtitle !== undefined) {
  97298. var element = metadataContainer.querySelector('span.model-subtitle');
  97299. if (element) {
  97300. element.innerHTML = modelConfiguration.subtitle;
  97301. }
  97302. }
  97303. if (modelConfiguration.thumbnail !== undefined) {
  97304. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  97305. }
  97306. }
  97307. };
  97308. /**
  97309. * This will load a new model to the default viewer
  97310. * overriding the AbstractViewer's loadModel.
  97311. * The scene will automatically be cleared of the old models, if exist.
  97312. * @param model the configuration object (or URL) to load.
  97313. */
  97314. DefaultViewer.prototype.loadModel = function (model) {
  97315. var _this = this;
  97316. if (model === void 0) { model = this._configuration.model; }
  97317. this.showLoadingScreen();
  97318. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  97319. console.log(error);
  97320. _this.hideLoadingScreen();
  97321. _this.showOverlayScreen('error');
  97322. return Promise.reject(error);
  97323. });
  97324. };
  97325. /**
  97326. * Show the overlay and the defined sub-screen.
  97327. * Mainly used for help and errors
  97328. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  97329. */
  97330. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  97331. var _this = this;
  97332. var template = this.templateManager.getTemplate('overlay');
  97333. if (!template)
  97334. return Promise.resolve('Overlay template not found');
  97335. return template.show((function (template) {
  97336. var canvasRect = _this.containerElement.getBoundingClientRect();
  97337. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  97338. template.parent.style.display = 'flex';
  97339. template.parent.style.width = canvasRect.width + "px";
  97340. template.parent.style.height = canvasRect.height + "px";
  97341. template.parent.style.opacity = "1";
  97342. var subTemplate = _this.templateManager.getTemplate(subScreen);
  97343. if (!subTemplate) {
  97344. return Promise.reject(subScreen + ' template not found');
  97345. }
  97346. return subTemplate.show((function (template) {
  97347. template.parent.style.display = 'flex';
  97348. return Promise.resolve(template);
  97349. }));
  97350. }));
  97351. };
  97352. /**
  97353. * Hide the overlay screen.
  97354. */
  97355. DefaultViewer.prototype.hideOverlayScreen = function () {
  97356. var template = this.templateManager.getTemplate('overlay');
  97357. if (!template)
  97358. return Promise.resolve('Overlay template not found');
  97359. return template.hide((function (template) {
  97360. template.parent.style.opacity = "0";
  97361. var onTransitionEnd = function () {
  97362. template.parent.removeEventListener("transitionend", onTransitionEnd);
  97363. template.parent.style.display = 'none';
  97364. };
  97365. template.parent.addEventListener("transitionend", onTransitionEnd);
  97366. var overlays = template.parent.querySelectorAll('.overlay');
  97367. if (overlays) {
  97368. for (var i = 0; i < overlays.length; ++i) {
  97369. var htmlElement = overlays.item(i);
  97370. htmlElement.style.display = 'none';
  97371. }
  97372. }
  97373. return Promise.resolve(template);
  97374. }));
  97375. };
  97376. /**
  97377. * Show the loading screen.
  97378. * The loading screen can be configured using the configuration object
  97379. */
  97380. DefaultViewer.prototype.showLoadingScreen = function () {
  97381. var _this = this;
  97382. var template = this.templateManager.getTemplate('loadingScreen');
  97383. if (!template)
  97384. return Promise.resolve('Loading Screen template not found');
  97385. return template.show((function (template) {
  97386. var canvasRect = _this.containerElement.getBoundingClientRect();
  97387. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  97388. template.parent.style.display = 'flex';
  97389. template.parent.style.width = canvasRect.width + "px";
  97390. template.parent.style.height = canvasRect.height + "px";
  97391. template.parent.style.opacity = "1";
  97392. // from the configuration!!!
  97393. template.parent.style.backgroundColor = "black";
  97394. return Promise.resolve(template);
  97395. }));
  97396. };
  97397. /**
  97398. * Hide the loading screen
  97399. */
  97400. DefaultViewer.prototype.hideLoadingScreen = function () {
  97401. var template = this.templateManager.getTemplate('loadingScreen');
  97402. if (!template)
  97403. return Promise.resolve('Loading Screen template not found');
  97404. return template.hide((function (template) {
  97405. template.parent.style.opacity = "0";
  97406. var onTransitionEnd = function () {
  97407. template.parent.removeEventListener("transitionend", onTransitionEnd);
  97408. template.parent.style.display = 'none';
  97409. };
  97410. template.parent.addEventListener("transitionend", onTransitionEnd);
  97411. return Promise.resolve(template);
  97412. }));
  97413. };
  97414. /**
  97415. * An extension of the light configuration of the abstract viewer.
  97416. * @param lightsConfiguration the light configuration to use
  97417. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  97418. */
  97419. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  97420. var _this = this;
  97421. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  97422. _super.prototype._configureLights.call(this, lightsConfiguration, model);
  97423. // labs feature - flashlight
  97424. if (this._configuration.lab && this._configuration.lab.flashlight) {
  97425. var pointerPosition = babylonjs_1.Vector3.Zero();
  97426. var lightTarget_1;
  97427. var angle = 0.5;
  97428. var exponent = Math.PI / 2;
  97429. if (typeof this._configuration.lab.flashlight === "object") {
  97430. exponent = this._configuration.lab.flashlight.exponent || exponent;
  97431. angle = this._configuration.lab.flashlight.angle || angle;
  97432. }
  97433. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  97434. if (typeof this._configuration.lab.flashlight === "object") {
  97435. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  97436. if (this._configuration.lab.flashlight.diffuse) {
  97437. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  97438. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  97439. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  97440. }
  97441. if (this._configuration.lab.flashlight.specular) {
  97442. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  97443. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  97444. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  97445. }
  97446. }
  97447. this.scene.constantlyUpdateMeshUnderPointer = true;
  97448. this.scene.onPointerObservable.add(function (eventData, eventState) {
  97449. if (eventData.type === 4 && eventData.pickInfo) {
  97450. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  97451. }
  97452. else {
  97453. lightTarget_1 = undefined;
  97454. }
  97455. });
  97456. var updateFlashlightFunction = function () {
  97457. if (_this.camera && flashlight) {
  97458. flashlight.position.copyFrom(_this.camera.position);
  97459. if (lightTarget_1) {
  97460. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  97461. }
  97462. }
  97463. };
  97464. this.scene.registerBeforeRender(updateFlashlightFunction);
  97465. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  97466. }
  97467. };
  97468. return DefaultViewer;
  97469. }(viewer_1.AbstractViewer));
  97470. exports.DefaultViewer = DefaultViewer;
  97471. /***/ }),
  97472. /* 6 */
  97473. /***/ (function(module, exports, __webpack_require__) {
  97474. "use strict";
  97475. Object.defineProperty(exports, "__esModule", { value: true });
  97476. var viewerManager_1 = __webpack_require__(4);
  97477. var templateManager_1 = __webpack_require__(23);
  97478. var loader_1 = __webpack_require__(26);
  97479. var babylonjs_1 = __webpack_require__(0);
  97480. var deepmerge = __webpack_require__(2);
  97481. var modelLoader_1 = __webpack_require__(14);
  97482. /**
  97483. * The AbstractViewr is the center of Babylon's viewer.
  97484. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  97485. */
  97486. var AbstractViewer = /** @class */ (function () {
  97487. function AbstractViewer(containerElement, initialConfiguration) {
  97488. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  97489. var _this = this;
  97490. this.containerElement = containerElement;
  97491. /**
  97492. * is this viewer disposed?
  97493. */
  97494. this._isDisposed = false;
  97495. /**
  97496. * The resize function that will be registered with the window object
  97497. */
  97498. this._resize = function () {
  97499. // Only resize if Canvas is in the DOM
  97500. if (!_this.isCanvasInDOM()) {
  97501. return;
  97502. }
  97503. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  97504. return;
  97505. }
  97506. _this.engine.resize();
  97507. };
  97508. /**
  97509. * render loop that will be executed by the engine
  97510. */
  97511. this._render = function () {
  97512. _this.scene && _this.scene.activeCamera && _this.scene.render();
  97513. };
  97514. // if exists, use the container id. otherwise, generate a random string.
  97515. if (containerElement.id) {
  97516. this.baseId = containerElement.id;
  97517. }
  97518. else {
  97519. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  97520. }
  97521. this.onSceneInitObservable = new babylonjs_1.Observable();
  97522. this.onEngineInitObservable = new babylonjs_1.Observable();
  97523. this.onModelLoadedObservable = new babylonjs_1.Observable();
  97524. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  97525. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  97526. this.onInitDoneObservable = new babylonjs_1.Observable();
  97527. this.onLoaderInitObservable = new babylonjs_1.Observable();
  97528. this._registeredOnBeforeRenderFunctions = [];
  97529. this.models = [];
  97530. this.modelLoader = new modelLoader_1.ModelLoader(this);
  97531. // add this viewer to the viewer manager
  97532. viewerManager_1.viewerManager.addViewer(this);
  97533. // create a new template manager. TODO - singleton?
  97534. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  97535. this._prepareContainerElement();
  97536. // extend the configuration
  97537. this._configurationLoader = new loader_1.ConfigurationLoader();
  97538. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  97539. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  97540. if (_this._configuration.observers) {
  97541. _this._configureObservers(_this._configuration.observers);
  97542. }
  97543. //this.updateConfiguration(configuration);
  97544. // initialize the templates
  97545. var templateConfiguration = _this._configuration.templates || {};
  97546. _this.templateManager.initTemplate(templateConfiguration);
  97547. // when done, execute onTemplatesLoaded()
  97548. _this.templateManager.onAllLoaded.add(function () {
  97549. var canvas = _this.templateManager.getCanvas();
  97550. if (canvas) {
  97551. _this._canvas = canvas;
  97552. }
  97553. _this._onTemplateLoaded();
  97554. });
  97555. });
  97556. }
  97557. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  97558. /**
  97559. * Returns a boolean representing HDR support
  97560. */
  97561. get: function () {
  97562. return this._hdrSupport;
  97563. },
  97564. enumerable: true,
  97565. configurable: true
  97566. });
  97567. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  97568. /**
  97569. * The (single) canvas of this viewer
  97570. */
  97571. get: function () {
  97572. return this._canvas;
  97573. },
  97574. enumerable: true,
  97575. configurable: true
  97576. });
  97577. /**
  97578. * get the baseId of this viewer
  97579. */
  97580. AbstractViewer.prototype.getBaseId = function () {
  97581. return this.baseId;
  97582. };
  97583. /**
  97584. * Do we have a canvas to render on, and is it a part of the scene
  97585. */
  97586. AbstractViewer.prototype.isCanvasInDOM = function () {
  97587. return !!this._canvas && !!this._canvas.parentElement;
  97588. };
  97589. /**
  97590. * Update the current viewer configuration with new values.
  97591. * Only provided information will be updated, old configuration values will be kept.
  97592. * If this.configuration was manually changed, you can trigger this function with no parameters,
  97593. * and the entire configuration will be updated.
  97594. * @param newConfiguration
  97595. */
  97596. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  97597. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  97598. // update this.configuration with the new data
  97599. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  97600. // update scene configuration
  97601. if (newConfiguration.scene) {
  97602. this._configureScene(newConfiguration.scene);
  97603. }
  97604. // optimizer
  97605. if (newConfiguration.optimizer) {
  97606. this._configureOptimizer(newConfiguration.optimizer);
  97607. }
  97608. // observers in configuration
  97609. if (newConfiguration.observers) {
  97610. this._configureObservers(newConfiguration.observers);
  97611. }
  97612. // configure model
  97613. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  97614. this._configureModel(newConfiguration.model);
  97615. }
  97616. // lights
  97617. if (newConfiguration.lights) {
  97618. this._configureLights(newConfiguration.lights);
  97619. }
  97620. // environment
  97621. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  97622. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  97623. }
  97624. // camera
  97625. if (newConfiguration.camera) {
  97626. this._configureCamera(newConfiguration.camera);
  97627. }
  97628. };
  97629. AbstractViewer.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  97630. if (!skyboxConifguration && !groundConfiguration) {
  97631. if (this.environmentHelper) {
  97632. this.environmentHelper.dispose();
  97633. delete this.environmentHelper;
  97634. }
  97635. ;
  97636. return Promise.resolve(this.scene);
  97637. }
  97638. var options = {
  97639. createGround: !!groundConfiguration,
  97640. createSkybox: !!skyboxConifguration,
  97641. setupImageProcessing: false // will be done at the scene level!
  97642. };
  97643. if (groundConfiguration) {
  97644. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  97645. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  97646. if (groundSize) {
  97647. options.groundSize = groundSize;
  97648. }
  97649. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  97650. if (groundConfig.shadowLevel !== undefined) {
  97651. options.groundShadowLevel = groundConfig.shadowLevel;
  97652. }
  97653. options.enableGroundMirror = !!groundConfig.mirror;
  97654. if (groundConfig.texture) {
  97655. options.groundTexture = groundConfig.texture;
  97656. }
  97657. if (groundConfig.color) {
  97658. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  97659. }
  97660. if (groundConfig.opacity !== undefined) {
  97661. options.groundOpacity = groundConfig.opacity;
  97662. }
  97663. if (groundConfig.mirror) {
  97664. options.enableGroundMirror = true;
  97665. // to prevent undefines
  97666. if (typeof groundConfig.mirror === "object") {
  97667. if (groundConfig.mirror.amount !== undefined)
  97668. options.groundMirrorAmount = groundConfig.mirror.amount;
  97669. if (groundConfig.mirror.sizeRatio !== undefined)
  97670. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  97671. if (groundConfig.mirror.blurKernel !== undefined)
  97672. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  97673. if (groundConfig.mirror.fresnelWeight !== undefined)
  97674. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  97675. if (groundConfig.mirror.fallOffDistance !== undefined)
  97676. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  97677. if (this._defaultPipelineTextureType !== undefined)
  97678. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  97679. }
  97680. }
  97681. }
  97682. var postInitSkyboxMaterial = false;
  97683. if (skyboxConifguration) {
  97684. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  97685. if (conf.material && conf.material.imageProcessingConfiguration) {
  97686. options.setupImageProcessing = false; // will be configured later manually.
  97687. }
  97688. var skyboxSize = conf.scale;
  97689. if (skyboxSize) {
  97690. options.skyboxSize = skyboxSize;
  97691. }
  97692. options.sizeAuto = !options.skyboxSize;
  97693. if (conf.color) {
  97694. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  97695. }
  97696. if (conf.cubeTexture && conf.cubeTexture.url) {
  97697. if (typeof conf.cubeTexture.url === "string") {
  97698. options.skyboxTexture = conf.cubeTexture.url;
  97699. }
  97700. else {
  97701. // init later!
  97702. postInitSkyboxMaterial = true;
  97703. }
  97704. }
  97705. if (conf.material && conf.material.imageProcessingConfiguration) {
  97706. postInitSkyboxMaterial = true;
  97707. }
  97708. }
  97709. options.setupImageProcessing = false; // TMP
  97710. if (!this.environmentHelper) {
  97711. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97712. }
  97713. else {
  97714. // there might be a new scene! we need to dispose.
  97715. // get the scene used by the envHelper
  97716. var scene = this.environmentHelper.rootMesh.getScene();
  97717. // is it a different scene? Oh no!
  97718. if (scene !== this.scene) {
  97719. this.environmentHelper.dispose();
  97720. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  97721. }
  97722. else {
  97723. this.environmentHelper.updateOptions(options);
  97724. }
  97725. }
  97726. if (postInitSkyboxMaterial) {
  97727. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  97728. if (skyboxMaterial) {
  97729. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  97730. this._extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  97731. }
  97732. }
  97733. }
  97734. };
  97735. /**
  97736. * internally configure the scene using the provided configuration.
  97737. * The scene will not be recreated, but just updated.
  97738. * @param sceneConfig the (new) scene configuration
  97739. */
  97740. AbstractViewer.prototype._configureScene = function (sceneConfig) {
  97741. // sanity check!
  97742. if (!this.scene) {
  97743. return;
  97744. }
  97745. if (sceneConfig.debug) {
  97746. this.scene.debugLayer.show();
  97747. }
  97748. else {
  97749. if (this.scene.debugLayer.isVisible()) {
  97750. this.scene.debugLayer.hide();
  97751. }
  97752. }
  97753. if (sceneConfig.clearColor) {
  97754. var cc = sceneConfig.clearColor;
  97755. var oldcc = this.scene.clearColor;
  97756. if (cc.r !== undefined) {
  97757. oldcc.r = cc.r;
  97758. }
  97759. if (cc.g !== undefined) {
  97760. oldcc.g = cc.g;
  97761. }
  97762. if (cc.b !== undefined) {
  97763. oldcc.b = cc.b;
  97764. }
  97765. if (cc.a !== undefined) {
  97766. oldcc.a = cc.a;
  97767. }
  97768. }
  97769. // image processing configuration - optional.
  97770. if (sceneConfig.imageProcessingConfiguration) {
  97771. this._extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  97772. }
  97773. if (sceneConfig.environmentTexture) {
  97774. if (this.scene.environmentTexture) {
  97775. this.scene.environmentTexture.dispose();
  97776. }
  97777. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  97778. this.scene.environmentTexture = environmentTexture;
  97779. }
  97780. if (sceneConfig.autoRotate) {
  97781. this.camera.useAutoRotationBehavior = true;
  97782. }
  97783. };
  97784. /**
  97785. * Configure the scene optimizer.
  97786. * The existing scene optimizer will be disposed and a new one will be created.
  97787. * @param optimizerConfig the (new) optimizer configuration
  97788. */
  97789. AbstractViewer.prototype._configureOptimizer = function (optimizerConfig) {
  97790. if (typeof optimizerConfig === 'boolean') {
  97791. if (this.sceneOptimizer) {
  97792. this.sceneOptimizer.stop();
  97793. this.sceneOptimizer.dispose();
  97794. delete this.sceneOptimizer;
  97795. }
  97796. if (optimizerConfig) {
  97797. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  97798. this.sceneOptimizer.start();
  97799. }
  97800. }
  97801. else {
  97802. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  97803. // check for degradation
  97804. if (optimizerConfig.degradation) {
  97805. switch (optimizerConfig.degradation) {
  97806. case "low":
  97807. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  97808. break;
  97809. case "moderate":
  97810. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  97811. break;
  97812. case "hight":
  97813. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  97814. break;
  97815. }
  97816. }
  97817. if (this.sceneOptimizer) {
  97818. this.sceneOptimizer.stop();
  97819. this.sceneOptimizer.dispose();
  97820. }
  97821. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  97822. this.sceneOptimizer.start();
  97823. }
  97824. };
  97825. /**
  97826. * this is used to register native functions using the configuration object.
  97827. * This will configure the observers.
  97828. * @param observersConfiguration observers configuration
  97829. */
  97830. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  97831. if (observersConfiguration.onEngineInit) {
  97832. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  97833. }
  97834. else {
  97835. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  97836. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  97837. }
  97838. }
  97839. if (observersConfiguration.onSceneInit) {
  97840. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  97841. }
  97842. else {
  97843. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  97844. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  97845. }
  97846. }
  97847. if (observersConfiguration.onModelLoaded) {
  97848. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  97849. }
  97850. else {
  97851. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  97852. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  97853. }
  97854. }
  97855. };
  97856. /**
  97857. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  97858. * @param cameraConfig the new camera configuration
  97859. * @param model optionally use the model to configure the camera.
  97860. */
  97861. AbstractViewer.prototype._configureCamera = function (cameraConfig, model) {
  97862. var _this = this;
  97863. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97864. if (!this.scene.activeCamera) {
  97865. this.scene.createDefaultCamera(true, true, true);
  97866. this.camera = this.scene.activeCamera;
  97867. }
  97868. if (cameraConfig.position) {
  97869. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  97870. }
  97871. if (cameraConfig.rotation) {
  97872. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  97873. }
  97874. this._extendClassWithConfig(this.camera, cameraConfig);
  97875. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  97876. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  97877. if (cameraConfig.behaviors) {
  97878. for (var name_1 in cameraConfig.behaviors) {
  97879. this._setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  97880. }
  97881. }
  97882. ;
  97883. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  97884. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  97885. });
  97886. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97887. var sceneDiagonalLenght = sceneDiagonal.length();
  97888. if (isFinite(sceneDiagonalLenght))
  97889. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  97890. };
  97891. /**
  97892. * configure the lights.
  97893. *
  97894. * @param lightsConfiguration the (new) light(s) configuration
  97895. * @param model optionally use the model to configure the camera.
  97896. */
  97897. AbstractViewer.prototype._configureLights = function (lightsConfiguration, model) {
  97898. var _this = this;
  97899. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  97900. var focusMeshes = model ? model.meshes : this.scene.meshes;
  97901. // sanity check!
  97902. if (!Object.keys(lightsConfiguration).length)
  97903. return;
  97904. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  97905. // compare to the global (!) configuration object and dispose unneeded:
  97906. var lightsToConfigure = Object.keys(this._configuration.lights || []);
  97907. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  97908. lightsAvailable.forEach(function (lName) {
  97909. if (lightsToConfigure.indexOf(lName) === -1) {
  97910. _this.scene.getLightByName(lName).dispose();
  97911. }
  97912. });
  97913. }
  97914. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  97915. var lightConfig = { type: 0 };
  97916. if (typeof lightsConfiguration[name] === 'object') {
  97917. lightConfig = lightsConfiguration[name];
  97918. }
  97919. lightConfig.name = name;
  97920. var light;
  97921. // light is not already available
  97922. if (lightsAvailable.indexOf(name) === -1) {
  97923. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97924. if (!constructor)
  97925. return;
  97926. light = constructor();
  97927. }
  97928. else {
  97929. // available? get it from the scene
  97930. light = _this.scene.getLightByName(name);
  97931. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  97932. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  97933. light.dispose();
  97934. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  97935. if (!constructor)
  97936. return;
  97937. light = constructor();
  97938. }
  97939. }
  97940. // if config set the light to false, dispose it.
  97941. if (lightsConfiguration[name] === false) {
  97942. light.dispose();
  97943. return;
  97944. }
  97945. //enabled
  97946. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  97947. light.setEnabled(enabled);
  97948. _this._extendClassWithConfig(light, lightConfig);
  97949. //position. Some lights don't support shadows
  97950. if (light instanceof babylonjs_1.ShadowLight) {
  97951. if (lightConfig.target) {
  97952. if (light.setDirectionToTarget) {
  97953. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  97954. light.setDirectionToTarget(target);
  97955. }
  97956. }
  97957. else if (lightConfig.direction) {
  97958. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  97959. light.direction = direction;
  97960. }
  97961. var shadowGenerator = light.getShadowGenerator();
  97962. if (lightConfig.shadowEnabled && _this._maxShadows) {
  97963. if (!shadowGenerator) {
  97964. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  97965. // TODO blur kernel definition
  97966. }
  97967. _this._extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  97968. // add the focues meshes to the shadow list
  97969. var shadownMap = shadowGenerator.getShadowMap();
  97970. if (!shadownMap)
  97971. return;
  97972. var renderList = shadownMap.renderList;
  97973. for (var index = 0; index < focusMeshes.length; index++) {
  97974. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  97975. renderList && renderList.push(focusMeshes[index]);
  97976. }
  97977. }
  97978. }
  97979. else if (shadowGenerator) {
  97980. shadowGenerator.dispose();
  97981. }
  97982. }
  97983. });
  97984. };
  97985. /**
  97986. * configure all models using the configuration.
  97987. * @param modelConfiguration the configuration to use to reconfigure the models
  97988. */
  97989. AbstractViewer.prototype._configureModel = function (modelConfiguration) {
  97990. this.models.forEach(function (model) {
  97991. model.updateConfiguration(modelConfiguration);
  97992. });
  97993. };
  97994. /**
  97995. * Dispoe the entire viewer including the scene and the engine
  97996. */
  97997. AbstractViewer.prototype.dispose = function () {
  97998. if (this._isDisposed) {
  97999. return;
  98000. }
  98001. window.removeEventListener('resize', this._resize);
  98002. if (this.sceneOptimizer) {
  98003. this.sceneOptimizer.stop();
  98004. this.sceneOptimizer.dispose();
  98005. }
  98006. if (this.environmentHelper) {
  98007. this.environmentHelper.dispose();
  98008. }
  98009. if (this._configurationLoader) {
  98010. this._configurationLoader.dispose();
  98011. }
  98012. //observers
  98013. this.onEngineInitObservable.clear();
  98014. delete this.onEngineInitObservable;
  98015. this.onInitDoneObservable.clear();
  98016. delete this.onInitDoneObservable;
  98017. this.onLoaderInitObservable.clear();
  98018. delete this.onLoaderInitObservable;
  98019. this.onModelLoadedObservable.clear();
  98020. delete this.onModelLoadedObservable;
  98021. this.onModelLoadErrorObservable.clear();
  98022. delete this.onModelLoadErrorObservable;
  98023. this.onModelLoadProgressObservable.clear();
  98024. delete this.onModelLoadProgressObservable;
  98025. this.onSceneInitObservable.clear();
  98026. delete this.onSceneInitObservable;
  98027. if (this.scene.activeCamera) {
  98028. this.scene.activeCamera.detachControl(this.canvas);
  98029. }
  98030. this.modelLoader.dispose();
  98031. this.models.forEach(function (model) {
  98032. model.dispose();
  98033. });
  98034. this.models.length = 0;
  98035. this.scene.dispose();
  98036. this.engine.dispose();
  98037. this.templateManager.dispose();
  98038. viewerManager_1.viewerManager.removeViewer(this);
  98039. this._isDisposed = true;
  98040. };
  98041. /**
  98042. * This function will execute when the HTML templates finished initializing.
  98043. * It should initialize the engine and continue execution.
  98044. *
  98045. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  98046. */
  98047. AbstractViewer.prototype._onTemplatesLoaded = function () {
  98048. return Promise.resolve(this);
  98049. };
  98050. /**
  98051. * This will force the creation of an engine and a scene.
  98052. * It will also load a model if preconfigured.
  98053. * But first - it will load the extendible onTemplateLoaded()!
  98054. */
  98055. AbstractViewer.prototype._onTemplateLoaded = function () {
  98056. var _this = this;
  98057. return this._onTemplatesLoaded().then(function () {
  98058. var autoLoadModel = _this._configuration.model;
  98059. return _this._initEngine().then(function (engine) {
  98060. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  98061. }).then(function () {
  98062. if (autoLoadModel) {
  98063. return _this.loadModel().catch(function (e) { }).then(function () { return _this.scene; });
  98064. }
  98065. else {
  98066. return _this.scene || _this._initScene();
  98067. }
  98068. }).then(function (scene) {
  98069. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  98070. }).then(function () {
  98071. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  98072. }).catch(function (e) {
  98073. babylonjs_1.Tools.Warn(e.toString());
  98074. return _this;
  98075. });
  98076. });
  98077. };
  98078. /**
  98079. * Initialize the engine. Retruns a promise in case async calls are needed.
  98080. *
  98081. * @protected
  98082. * @returns {Promise<Engine>}
  98083. * @memberof Viewer
  98084. */
  98085. AbstractViewer.prototype._initEngine = function () {
  98086. // init custom shaders
  98087. this._injectCustomShaders();
  98088. var canvasElement = this.templateManager.getCanvas();
  98089. if (!canvasElement) {
  98090. return Promise.reject('Canvas element not found!');
  98091. }
  98092. var config = this._configuration.engine || {};
  98093. // TDO enable further configuration
  98094. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  98095. // Disable manifest checking
  98096. babylonjs_1.Database.IDBStorageEnabled = false;
  98097. if (!config.disableResize) {
  98098. window.addEventListener('resize', this._resize);
  98099. }
  98100. this.engine.runRenderLoop(this._render);
  98101. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  98102. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  98103. this.engine.setHardwareScalingLevel(scale);
  98104. }
  98105. // set hardware limitations for scene initialization
  98106. this._handleHardwareLimitations();
  98107. return Promise.resolve(this.engine);
  98108. };
  98109. /**
  98110. * initialize the scene. Calling thsi function again will dispose the old scene, if exists.
  98111. */
  98112. AbstractViewer.prototype._initScene = function () {
  98113. // if the scen exists, dispose it.
  98114. if (this.scene) {
  98115. this.scene.dispose();
  98116. }
  98117. // create a new scene
  98118. this.scene = new babylonjs_1.Scene(this.engine);
  98119. // make sure there is a default camera and light.
  98120. this.scene.createDefaultLight(true);
  98121. if (this._configuration.scene) {
  98122. this._configureScene(this._configuration.scene);
  98123. // Scene optimizer
  98124. if (this._configuration.optimizer) {
  98125. this._configureOptimizer(this._configuration.optimizer);
  98126. }
  98127. }
  98128. return Promise.resolve(this.scene);
  98129. };
  98130. /**
  98131. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  98132. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  98133. *
  98134. * @param modelConfig model configuration to use when loading the model.
  98135. * @param clearScene should the scene be cleared before loading this model
  98136. * @returns a ViewerModel object that is not yet fully loaded.
  98137. */
  98138. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  98139. var _this = this;
  98140. if (clearScene === void 0) { clearScene = true; }
  98141. if (clearScene) {
  98142. this.models.forEach(function (m) { return m.dispose(); });
  98143. this.models.length = 0;
  98144. }
  98145. var model = this.modelLoader.load(modelConfig);
  98146. this.lastUsedLoader = model.loader;
  98147. model.onLoadErrorObservable.add(function (errorObject) {
  98148. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  98149. });
  98150. model.onLoadProgressObservable.add(function (progressEvent) {
  98151. return _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  98152. });
  98153. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  98154. model.onLoadedObservable.add(function () {
  98155. _this.onModelLoadedObservable.notifyObserversWithPromise(model)
  98156. .then(function () {
  98157. _this._configureLights(_this._configuration.lights);
  98158. if (_this._configuration.camera || !_this.scene.activeCamera) {
  98159. _this._configureCamera(_this._configuration.camera || {}, model);
  98160. }
  98161. return _this._initEnvironment(model);
  98162. }).then(function () {
  98163. _this._isLoading = false;
  98164. return model;
  98165. });
  98166. });
  98167. return model;
  98168. };
  98169. /**
  98170. * load a model using the provided configuration
  98171. *
  98172. * @param modelConfig the model configuration or URL to load.
  98173. * @param clearScene Should the scene be cleared before loading the model
  98174. * @returns a Promise the fulfills when the model finished loading successfully.
  98175. */
  98176. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  98177. var _this = this;
  98178. if (modelConfig === void 0) { modelConfig = this._configuration.model; }
  98179. if (clearScene === void 0) { clearScene = true; }
  98180. // no model was provided? Do nothing!
  98181. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  98182. if (!modelUrl) {
  98183. return Promise.reject("no model configuration found");
  98184. }
  98185. if (this._isLoading) {
  98186. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  98187. return Promise.reject("another model is curently being loaded.");
  98188. }
  98189. this._isLoading = true;
  98190. if ((typeof modelConfig === 'string')) {
  98191. if (this._configuration.model && typeof this._configuration.model === 'object') {
  98192. this._configuration.model.url = modelConfig;
  98193. }
  98194. }
  98195. else {
  98196. if (this._configuration.model) {
  98197. deepmerge(this._configuration.model, modelConfig);
  98198. }
  98199. else {
  98200. this._configuration.model = modelConfig;
  98201. }
  98202. }
  98203. return Promise.resolve(this.scene).then(function (scene) {
  98204. if (!scene)
  98205. return _this._initScene();
  98206. return scene;
  98207. }).then(function () {
  98208. return new Promise(function (resolve, reject) {
  98209. // at this point, configuration.model is an object, not a string
  98210. return _this.initModel(modelConfig, clearScene);
  98211. });
  98212. });
  98213. };
  98214. /**
  98215. * initialize the environment for a specific model.
  98216. * Per default it will use the viewer'S configuration.
  98217. * @param model the model to use to configure the environment.
  98218. * @returns a Promise that will resolve when the configuration is done.
  98219. */
  98220. AbstractViewer.prototype._initEnvironment = function (model) {
  98221. this._configureEnvironment(this._configuration.skybox, this._configuration.ground);
  98222. return Promise.resolve(this.scene);
  98223. };
  98224. /**
  98225. * Alters render settings to reduce features based on hardware feature limitations
  98226. * @param enableHDR Allows the viewer to run in HDR mode.
  98227. */
  98228. AbstractViewer.prototype._handleHardwareLimitations = function (enableHDR) {
  98229. if (enableHDR === void 0) { enableHDR = true; }
  98230. //flip rendering settings switches based on hardware support
  98231. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  98232. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  98233. //shadows are disabled if there's not enough varyings for a single shadow
  98234. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  98235. this._maxShadows = 0;
  98236. }
  98237. else {
  98238. this._maxShadows = 3;
  98239. }
  98240. //can we render to any >= 16-bit targets (required for HDR)
  98241. var caps = this.engine.getCaps();
  98242. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  98243. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  98244. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  98245. if (linearHalfFloatTargets) {
  98246. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  98247. this._shadowGeneratorBias = 0.002;
  98248. }
  98249. else if (linearFloatTargets) {
  98250. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  98251. this._shadowGeneratorBias = 0.001;
  98252. }
  98253. else {
  98254. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  98255. this._shadowGeneratorBias = 0.001;
  98256. }
  98257. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  98258. };
  98259. /**
  98260. * Injects all the spectre shader in the babylon shader store
  98261. */
  98262. AbstractViewer.prototype._injectCustomShaders = function () {
  98263. var customShaders = this._configuration.customShaders;
  98264. // Inject all the spectre shader in the babylon shader store.
  98265. if (!customShaders) {
  98266. return;
  98267. }
  98268. if (customShaders.shaders) {
  98269. Object.keys(customShaders.shaders).forEach(function (key) {
  98270. // typescript considers a callback "unsafe", so... '!'
  98271. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  98272. });
  98273. }
  98274. if (customShaders.includes) {
  98275. Object.keys(customShaders.includes).forEach(function (key) {
  98276. // typescript considers a callback "unsafe", so... '!'
  98277. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  98278. });
  98279. }
  98280. };
  98281. /**
  98282. * This will extend an object with configuration values.
  98283. * What it practically does it take the keys from the configuration and set them on the object.
  98284. * I the configuration is a tree, it will traverse into the tree.
  98285. * @param object the object to extend
  98286. * @param config the configuration object that will extend the object
  98287. */
  98288. AbstractViewer.prototype._extendClassWithConfig = function (object, config) {
  98289. var _this = this;
  98290. if (!config)
  98291. return;
  98292. Object.keys(config).forEach(function (key) {
  98293. if (key in object && typeof object[key] !== 'function') {
  98294. // if (typeof object[key] === 'function') return;
  98295. // if it is an object, iterate internally until reaching basic types
  98296. if (typeof object[key] === 'object') {
  98297. _this._extendClassWithConfig(object[key], config[key]);
  98298. }
  98299. else {
  98300. if (config[key] !== undefined) {
  98301. object[key] = config[key];
  98302. }
  98303. }
  98304. }
  98305. });
  98306. };
  98307. AbstractViewer.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  98308. var behavior;
  98309. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  98310. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  98311. // constructing behavior
  98312. switch (type) {
  98313. case 0 /* AUTOROTATION */:
  98314. this.camera.useAutoRotationBehavior = true;
  98315. behavior = this.camera.autoRotationBehavior;
  98316. break;
  98317. case 1 /* BOUNCING */:
  98318. this.camera.useBouncingBehavior = true;
  98319. behavior = this.camera.bouncingBehavior;
  98320. break;
  98321. case 2 /* FRAMING */:
  98322. this.camera.useFramingBehavior = true;
  98323. behavior = this.camera.framingBehavior;
  98324. break;
  98325. default:
  98326. behavior = null;
  98327. break;
  98328. }
  98329. if (behavior) {
  98330. if (typeof behaviorConfig === "object") {
  98331. this._extendClassWithConfig(behavior, behaviorConfig);
  98332. }
  98333. }
  98334. // post attach configuration. Some functionalities require the attached camera.
  98335. switch (type) {
  98336. case 0 /* AUTOROTATION */:
  98337. break;
  98338. case 1 /* BOUNCING */:
  98339. break;
  98340. case 2 /* FRAMING */:
  98341. if (config.zoomOnBoundingInfo) {
  98342. //payload is an array of meshes
  98343. var meshes = payload;
  98344. var bounding = meshes[0].getHierarchyBoundingVectors();
  98345. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  98346. }
  98347. break;
  98348. }
  98349. };
  98350. return AbstractViewer;
  98351. }());
  98352. exports.AbstractViewer = AbstractViewer;
  98353. /***/ }),
  98354. /* 7 */
  98355. /***/ (function(module, exports) {
  98356. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  98357. /***/ }),
  98358. /* 8 */
  98359. /***/ (function(module, exports) {
  98360. 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}}>";
  98361. /***/ }),
  98362. /* 9 */
  98363. /***/ (function(module, exports) {
  98364. 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=="
  98365. /***/ }),
  98366. /* 10 */
  98367. /***/ (function(module, exports) {
  98368. 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>";
  98369. /***/ }),
  98370. /* 11 */
  98371. /***/ (function(module, exports) {
  98372. 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>";
  98373. /***/ }),
  98374. /* 12 */
  98375. /***/ (function(module, exports) {
  98376. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  98377. /***/ }),
  98378. /* 13 */
  98379. /***/ (function(module, exports) {
  98380. module.exports = "Error loading the model";
  98381. /***/ }),
  98382. /* 14 */
  98383. /***/ (function(module, exports, __webpack_require__) {
  98384. "use strict";
  98385. Object.defineProperty(exports, "__esModule", { value: true });
  98386. var babylonjs_1 = __webpack_require__(0);
  98387. var viewerModel_1 = __webpack_require__(15);
  98388. /**
  98389. * An instance of the class is in charge of loading the model correctly.
  98390. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  98391. *
  98392. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  98393. */
  98394. var ModelLoader = /** @class */ (function () {
  98395. /**
  98396. * Create a new Model loader
  98397. * @param _viewer the viewer using this model loader
  98398. */
  98399. function ModelLoader(_viewer) {
  98400. this._viewer = _viewer;
  98401. this._disposed = false;
  98402. this._loaders = [];
  98403. this._loadId = 0;
  98404. }
  98405. /**
  98406. * Load a model using predefined configuration
  98407. * @param modelConfiguration the modelConfiguration to use to load the model
  98408. */
  98409. ModelLoader.prototype.load = function (modelConfiguration) {
  98410. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  98411. if (!modelConfiguration.url) {
  98412. model.state = viewerModel_1.ModelState.ERROR;
  98413. babylonjs_1.Tools.Error("No URL provided");
  98414. return model;
  98415. }
  98416. var filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  98417. var base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  98418. var plugin = modelConfiguration.loader;
  98419. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  98420. meshes.forEach(function (mesh) {
  98421. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  98422. });
  98423. model.meshes = meshes;
  98424. model.particleSystems = particleSystems;
  98425. model.skeletons = skeletons;
  98426. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  98427. var animationGroup = animationGroups_1[_i];
  98428. model.addAnimationGroup(animationGroup);
  98429. }
  98430. model.initAnimations();
  98431. model.onLoadedObservable.notifyObserversWithPromise(model);
  98432. }, function (progressEvent) {
  98433. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  98434. }, function (e, m, exception) {
  98435. model.state = viewerModel_1.ModelState.ERROR;
  98436. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  98437. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  98438. }, plugin);
  98439. if (model.loader.name === "gltf") {
  98440. var gltfLoader = model.loader;
  98441. gltfLoader.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.NONE;
  98442. }
  98443. model.loadId = this._loadId++;
  98444. this._loaders.push(model.loader);
  98445. return model;
  98446. };
  98447. ModelLoader.prototype.cancelLoad = function (model) {
  98448. var loader = model.loader || this._loaders[model.loadId];
  98449. // ATM only available in the GLTF Loader
  98450. if (loader && loader.name === "gltf") {
  98451. var gltfLoader = loader;
  98452. gltfLoader.dispose();
  98453. model.state = viewerModel_1.ModelState.CANCELED;
  98454. }
  98455. else {
  98456. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  98457. }
  98458. };
  98459. /**
  98460. * dispose the model loader.
  98461. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  98462. */
  98463. ModelLoader.prototype.dispose = function () {
  98464. this._loaders.forEach(function (loader) {
  98465. if (loader.name === "gltf") {
  98466. loader.dispose();
  98467. }
  98468. });
  98469. this._loaders.length = 0;
  98470. this._disposed = true;
  98471. };
  98472. return ModelLoader;
  98473. }());
  98474. exports.ModelLoader = ModelLoader;
  98475. /***/ }),
  98476. /* 15 */
  98477. /***/ (function(module, exports, __webpack_require__) {
  98478. "use strict";
  98479. Object.defineProperty(exports, "__esModule", { value: true });
  98480. var babylonjs_1 = __webpack_require__(0);
  98481. var modelAnimation_1 = __webpack_require__(16);
  98482. var deepmerge = __webpack_require__(2);
  98483. var ModelState;
  98484. (function (ModelState) {
  98485. ModelState[ModelState["INIT"] = 0] = "INIT";
  98486. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  98487. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  98488. ModelState[ModelState["CANCELED"] = 3] = "CANCELED";
  98489. ModelState[ModelState["ERROR"] = 4] = "ERROR";
  98490. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  98491. /**
  98492. * The viewer model is a container for all assets representing a sngle loaded model.
  98493. */
  98494. var ViewerModel = /** @class */ (function () {
  98495. function ViewerModel(_viewer, modelConfiguration) {
  98496. this._viewer = _viewer;
  98497. /**
  98498. * the list of meshes that are a part of this model
  98499. */
  98500. this.meshes = [];
  98501. /**
  98502. * ParticleSystems connected to this model
  98503. */
  98504. this.particleSystems = [];
  98505. /**
  98506. * Skeletons defined in this model
  98507. */
  98508. this.skeletons = [];
  98509. this.onLoadedObservable = new babylonjs_1.Observable();
  98510. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98511. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98512. this.onAfterConfigure = new babylonjs_1.Observable();
  98513. this.state = ModelState.INIT;
  98514. this._animations = [];
  98515. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98516. this._modelConfiguration = deepmerge({}, modelConfiguration);
  98517. this._viewer.models.push(this);
  98518. }
  98519. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98520. /**
  98521. * Get the model's configuration
  98522. */
  98523. get: function () {
  98524. return this._modelConfiguration;
  98525. },
  98526. /**
  98527. * (Re-)set the model's entire configuration
  98528. * @param newConfiguration the new configuration to replace the new one
  98529. */
  98530. set: function (newConfiguration) {
  98531. this._modelConfiguration = newConfiguration;
  98532. this._configureModel();
  98533. },
  98534. enumerable: true,
  98535. configurable: true
  98536. });
  98537. /**
  98538. * Update the current configuration with new values.
  98539. * Configuration will not be overwritten, but merged with the new configuration.
  98540. * Priority is to the new configuration
  98541. * @param newConfiguration the configuration to be merged into the current configuration;
  98542. */
  98543. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98544. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98545. this._configureModel();
  98546. };
  98547. ViewerModel.prototype.initAnimations = function () {
  98548. var _this = this;
  98549. this._animations.forEach(function (a) {
  98550. a.dispose();
  98551. });
  98552. this._animations.length = 0;
  98553. // check if this is not a gltf loader and init the animations
  98554. if (this.loader.name !== 'gltf') {
  98555. this.skeletons.forEach(function (skeleton, idx) {
  98556. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.scene);
  98557. skeleton.getAnimatables().forEach(function (a) {
  98558. if (a.animations[0]) {
  98559. ag.addTargetedAnimation(a.animations[0], a);
  98560. }
  98561. });
  98562. _this.addAnimationGroup(ag);
  98563. });
  98564. }
  98565. if (!this._modelConfiguration)
  98566. return;
  98567. if (this._modelConfiguration.animation) {
  98568. if (this._modelConfiguration.animation.playOnce) {
  98569. this._animations.forEach(function (a) {
  98570. a.playMode = modelAnimation_1.AnimationPlayMode.ONCE;
  98571. });
  98572. }
  98573. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98574. var animationName = this._modelConfiguration.animation.autoStart === true ?
  98575. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98576. this.playAnimation(animationName);
  98577. }
  98578. }
  98579. };
  98580. /**
  98581. * Add a new animation group to this model.
  98582. * @param animationGroup the new animation group to be added
  98583. */
  98584. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98585. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98586. };
  98587. /**
  98588. * Get the ModelAnimation array
  98589. */
  98590. ViewerModel.prototype.getAnimations = function () {
  98591. return this._animations;
  98592. };
  98593. /**
  98594. * Get the animations' names. Using the names you can play a specific animation.
  98595. */
  98596. ViewerModel.prototype.getAnimationNames = function () {
  98597. return this._animations.map(function (a) { return a.name; });
  98598. };
  98599. /**
  98600. * Get an animation by the provided name. Used mainly when playing n animation.
  98601. * @param name the name of the animation to find
  98602. */
  98603. ViewerModel.prototype._getAnimationByName = function (name) {
  98604. // can't use .find, noe available on IE
  98605. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98606. // what the next line means - if two animations have the same name, they will not be returned!
  98607. if (filtered.length === 1) {
  98608. return filtered[0];
  98609. }
  98610. else {
  98611. return null;
  98612. }
  98613. };
  98614. /**
  98615. * Choose an initialized animation using its name and start playing it
  98616. * @param name the name of the animation to play
  98617. * @returns The model aniamtion to be played.
  98618. */
  98619. ViewerModel.prototype.playAnimation = function (name) {
  98620. var animation = this._getAnimationByName(name);
  98621. if (animation) {
  98622. if (this.currentAnimation) {
  98623. this.currentAnimation.stop();
  98624. }
  98625. this.currentAnimation = animation;
  98626. animation.start();
  98627. return animation;
  98628. }
  98629. else {
  98630. throw new Error("animation not found - " + name);
  98631. }
  98632. };
  98633. ViewerModel.prototype._configureModel = function () {
  98634. var meshesWithNoParent = this.meshes.filter(function (m) { return !m.parent; });
  98635. var updateMeshesWithNoParent = function (variable, value, param) {
  98636. meshesWithNoParent.forEach(function (mesh) {
  98637. if (param) {
  98638. mesh[variable][param] = value;
  98639. }
  98640. else {
  98641. mesh[variable] = value;
  98642. }
  98643. });
  98644. };
  98645. var updateXYZ = function (variable, configValues) {
  98646. if (configValues.x !== undefined) {
  98647. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98648. }
  98649. if (configValues.y !== undefined) {
  98650. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98651. }
  98652. if (configValues.z !== undefined) {
  98653. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98654. }
  98655. if (configValues.w !== undefined) {
  98656. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98657. }
  98658. };
  98659. // position?
  98660. if (this._modelConfiguration.position) {
  98661. updateXYZ('position', this._modelConfiguration.position);
  98662. }
  98663. if (this._modelConfiguration.rotation) {
  98664. //quaternion?
  98665. if (this._modelConfiguration.rotation.w) {
  98666. meshesWithNoParent.forEach(function (mesh) {
  98667. if (!mesh.rotationQuaternion) {
  98668. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98669. }
  98670. });
  98671. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98672. }
  98673. else {
  98674. updateXYZ('rotation', this._modelConfiguration.rotation);
  98675. }
  98676. }
  98677. if (this._modelConfiguration.scaling) {
  98678. updateXYZ('scaling', this._modelConfiguration.scaling);
  98679. }
  98680. if (this._modelConfiguration.castShadow) {
  98681. this.meshes.forEach(function (mesh) {
  98682. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98683. });
  98684. }
  98685. if (this._modelConfiguration.normalize) {
  98686. var center = false;
  98687. var unitSize = false;
  98688. var parentIndex = void 0;
  98689. if (this._modelConfiguration.normalize === true) {
  98690. center = true;
  98691. unitSize = true;
  98692. parentIndex = 0;
  98693. }
  98694. else {
  98695. center = !!this._modelConfiguration.normalize.center;
  98696. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98697. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98698. }
  98699. var meshesToNormalize = [];
  98700. if (parentIndex !== undefined) {
  98701. meshesToNormalize.push(this.meshes[parentIndex]);
  98702. }
  98703. else {
  98704. meshesToNormalize = meshesWithNoParent;
  98705. }
  98706. if (unitSize) {
  98707. meshesToNormalize.forEach(function (mesh) {
  98708. mesh.normalizeToUnitCube(true);
  98709. mesh.computeWorldMatrix(true);
  98710. });
  98711. }
  98712. if (center) {
  98713. meshesToNormalize.forEach(function (mesh) {
  98714. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98715. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98716. var halfSizeVec = sizeVec.scale(0.5);
  98717. var center = boundingInfo.min.add(halfSizeVec);
  98718. mesh.position = center.scale(-1);
  98719. // Set on ground.
  98720. mesh.position.y += halfSizeVec.y;
  98721. // Recompute Info.
  98722. mesh.computeWorldMatrix(true);
  98723. });
  98724. }
  98725. }
  98726. this.onAfterConfigure.notifyObservers(this);
  98727. };
  98728. /**
  98729. * Dispose this model, including all of its associated assets.
  98730. */
  98731. ViewerModel.prototype.dispose = function () {
  98732. this.onAfterConfigure.clear();
  98733. this.onLoadedObservable.clear();
  98734. this.onLoadErrorObservable.clear();
  98735. this.onLoadProgressObservable.clear();
  98736. if (this.loader && this.loader.name === "gltf") {
  98737. this.loader.dispose();
  98738. }
  98739. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98740. this.particleSystems.length = 0;
  98741. this.skeletons.forEach(function (s) { return s.dispose(); });
  98742. this.skeletons.length = 0;
  98743. this._animations.forEach(function (ag) { return ag.dispose(); });
  98744. this._animations.length = 0;
  98745. this.meshes.forEach(function (m) { return m.dispose(); });
  98746. this.meshes.length = 0;
  98747. this._viewer.models.splice(this._viewer.models.indexOf(this), 1);
  98748. };
  98749. return ViewerModel;
  98750. }());
  98751. exports.ViewerModel = ViewerModel;
  98752. /***/ }),
  98753. /* 16 */
  98754. /***/ (function(module, exports, __webpack_require__) {
  98755. "use strict";
  98756. Object.defineProperty(exports, "__esModule", { value: true });
  98757. /**
  98758. * Animation play mode enum - is the animation looping or playing once
  98759. */
  98760. var AnimationPlayMode;
  98761. (function (AnimationPlayMode) {
  98762. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  98763. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  98764. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  98765. /**
  98766. * An enum representing the current state of an animation object
  98767. */
  98768. var AnimationState;
  98769. (function (AnimationState) {
  98770. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  98771. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  98772. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  98773. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  98774. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  98775. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  98776. /**
  98777. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  98778. * native GroupAnimation class.
  98779. */
  98780. var GroupModelAnimation = /** @class */ (function () {
  98781. /**
  98782. * Create a new GroupModelAnimation object using an AnimationGroup object
  98783. * @param _animationGroup The aniamtion group to base the class on
  98784. */
  98785. function GroupModelAnimation(_animationGroup) {
  98786. var _this = this;
  98787. this._animationGroup = _animationGroup;
  98788. this._state = AnimationState.INIT;
  98789. this._playMode = AnimationPlayMode.LOOP;
  98790. this._animationGroup.onAnimationEndObservable.add(function () {
  98791. _this.stop();
  98792. _this._state = AnimationState.ENDED;
  98793. });
  98794. }
  98795. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  98796. /**
  98797. * Get the animation's name
  98798. */
  98799. get: function () {
  98800. return this._animationGroup.name;
  98801. },
  98802. enumerable: true,
  98803. configurable: true
  98804. });
  98805. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  98806. /**
  98807. * Get the current animation's state
  98808. */
  98809. get: function () {
  98810. return this._state;
  98811. },
  98812. enumerable: true,
  98813. configurable: true
  98814. });
  98815. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  98816. /**
  98817. * Gets the speed ratio to use for all animations
  98818. */
  98819. get: function () {
  98820. return this._animationGroup.speedRatio;
  98821. },
  98822. /**
  98823. * Sets the speed ratio to use for all animations
  98824. */
  98825. set: function (value) {
  98826. this._animationGroup.speedRatio = value;
  98827. },
  98828. enumerable: true,
  98829. configurable: true
  98830. });
  98831. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  98832. /**
  98833. * Get the max numbers of frame available in the animation group
  98834. *
  98835. * In correlation to an arry, this would be ".length"
  98836. */
  98837. get: function () {
  98838. var animationFrames = this._animationGroup.targetedAnimations.map(function (ta) {
  98839. var keys = ta.animation.getKeys();
  98840. return keys[keys.length - 1].frame;
  98841. });
  98842. return Math.max.apply(null, animationFrames);
  98843. },
  98844. enumerable: true,
  98845. configurable: true
  98846. });
  98847. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  98848. /**
  98849. * Get the current frame playing right now.
  98850. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  98851. *
  98852. * In correlation to an array, this would be the current index
  98853. */
  98854. get: function () {
  98855. // get the first currentFrame found
  98856. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98857. var animatable = this._animationGroup.animatables[i];
  98858. var animations = animatable.getAnimations();
  98859. if (!animations || !animations.length) {
  98860. continue;
  98861. }
  98862. for (var idx = 0; idx < animations.length; ++idx) {
  98863. if (animations[idx].currentFrame) {
  98864. return animations[idx].currentFrame;
  98865. }
  98866. }
  98867. }
  98868. return 0;
  98869. },
  98870. enumerable: true,
  98871. configurable: true
  98872. });
  98873. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  98874. /**
  98875. * Get the FPS value of this animation
  98876. */
  98877. get: function () {
  98878. // get the first currentFrame found
  98879. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  98880. var animatable = this._animationGroup.animatables[i];
  98881. var animations = animatable.getAnimations();
  98882. if (!animations || !animations.length) {
  98883. continue;
  98884. }
  98885. for (var idx = 0; idx < animations.length; ++idx) {
  98886. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  98887. return animations[idx].animation.framePerSecond;
  98888. }
  98889. }
  98890. }
  98891. return 0;
  98892. },
  98893. enumerable: true,
  98894. configurable: true
  98895. });
  98896. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  98897. /**
  98898. * What is the animation'S play mode (looping or played once)
  98899. */
  98900. get: function () {
  98901. return this._playMode;
  98902. },
  98903. /**
  98904. * Set the play mode.
  98905. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  98906. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  98907. */
  98908. set: function (value) {
  98909. if (value === this._playMode) {
  98910. return;
  98911. }
  98912. this._playMode = value;
  98913. if (this.state === AnimationState.PLAYING) {
  98914. this._animationGroup.play(this._playMode === AnimationPlayMode.LOOP);
  98915. }
  98916. else {
  98917. this._animationGroup.reset();
  98918. this._state = AnimationState.INIT;
  98919. }
  98920. },
  98921. enumerable: true,
  98922. configurable: true
  98923. });
  98924. /**
  98925. * Reset the animation group
  98926. */
  98927. GroupModelAnimation.prototype.reset = function () {
  98928. this._animationGroup.reset();
  98929. };
  98930. /**
  98931. * Restart the animation group
  98932. */
  98933. GroupModelAnimation.prototype.restart = function () {
  98934. this._animationGroup.restart();
  98935. };
  98936. /**
  98937. *
  98938. * @param frameNumber Go to a specific frame in the animation
  98939. */
  98940. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  98941. // this._animationGroup.goToFrame(frameNumber);
  98942. this._animationGroup['_animatables'].forEach(function (a) {
  98943. a.goToFrame(frameNumber);
  98944. });
  98945. };
  98946. /**
  98947. * Start playing the animation.
  98948. */
  98949. GroupModelAnimation.prototype.start = function () {
  98950. this._animationGroup.start(this.playMode === AnimationPlayMode.LOOP, this.speedRatio);
  98951. if (this._animationGroup.isStarted) {
  98952. this._state = AnimationState.PLAYING;
  98953. }
  98954. };
  98955. /**
  98956. * Pause the animation
  98957. */
  98958. GroupModelAnimation.prototype.pause = function () {
  98959. this._animationGroup.pause();
  98960. this._state = AnimationState.PAUSED;
  98961. };
  98962. /**
  98963. * Stop the animation.
  98964. * This will fail silently if the animation group is already stopped.
  98965. */
  98966. GroupModelAnimation.prototype.stop = function () {
  98967. this._animationGroup.stop();
  98968. if (!this._animationGroup.isStarted) {
  98969. this._state = AnimationState.STOPPED;
  98970. }
  98971. };
  98972. /**
  98973. * Dispose this animation object.
  98974. */
  98975. GroupModelAnimation.prototype.dispose = function () {
  98976. this._animationGroup.dispose();
  98977. };
  98978. return GroupModelAnimation;
  98979. }());
  98980. exports.GroupModelAnimation = GroupModelAnimation;
  98981. /***/ }),
  98982. /* 17 */
  98983. /***/ (function(module, exports, __webpack_require__) {
  98984. module.exports = __webpack_require__(18);
  98985. /***/ }),
  98986. /* 18 */
  98987. /***/ (function(module, exports, __webpack_require__) {
  98988. "use strict";
  98989. Object.defineProperty(exports, "__esModule", { value: true });
  98990. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98991. var mappers_1 = __webpack_require__(1);
  98992. exports.mapperManager = mappers_1.mapperManager;
  98993. var viewerManager_1 = __webpack_require__(4);
  98994. exports.viewerManager = viewerManager_1.viewerManager;
  98995. var defaultViewer_1 = __webpack_require__(5);
  98996. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98997. var viewer_1 = __webpack_require__(6);
  98998. exports.AbstractViewer = viewer_1.AbstractViewer;
  98999. var modelLoader_1 = __webpack_require__(14);
  99000. exports.ModelLoader = modelLoader_1.ModelLoader;
  99001. var viewerModel_1 = __webpack_require__(15);
  99002. exports.ViewerModel = viewerModel_1.ViewerModel;
  99003. exports.ModelState = viewerModel_1.ModelState;
  99004. var modelAnimation_1 = __webpack_require__(16);
  99005. exports.AnimationPlayMode = modelAnimation_1.AnimationPlayMode;
  99006. exports.AnimationState = modelAnimation_1.AnimationState;
  99007. /**
  99008. * BabylonJS Viewer
  99009. *
  99010. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  99011. */
  99012. var babylonjs_1 = __webpack_require__(0);
  99013. // load needed modules.
  99014. __webpack_require__(34);
  99015. __webpack_require__(35);
  99016. var initializer_1 = __webpack_require__(36);
  99017. exports.InitTags = initializer_1.InitTags;
  99018. // promise polyfill, if needed!
  99019. babylonjs_1.PromisePolyfill.Apply();
  99020. exports.disableInit = false;
  99021. document.addEventListener("DOMContentLoaded", init);
  99022. function init(event) {
  99023. document.removeEventListener("DOMContentLoaded", init);
  99024. if (exports.disableInit)
  99025. return;
  99026. initializer_1.InitTags();
  99027. }
  99028. /**
  99029. * Dispose all viewers currently registered
  99030. */
  99031. function disposeAll() {
  99032. viewerManager_1.viewerManager.dispose();
  99033. mappers_1.mapperManager.dispose();
  99034. }
  99035. exports.disposeAll = disposeAll;
  99036. /***/ }),
  99037. /* 19 */
  99038. /***/ (function(module, exports) {
  99039. var g;
  99040. // This works in non-strict mode
  99041. g = (function() {
  99042. return this;
  99043. })();
  99044. try {
  99045. // This works if eval is allowed (see CSP)
  99046. g = g || Function("return this")() || (1,eval)("this");
  99047. } catch(e) {
  99048. // This works if the window reference is available
  99049. if(typeof window === "object")
  99050. g = window;
  99051. }
  99052. // g can still be undefined, but nothing to do about it...
  99053. // We return undefined, instead of nothing here, so it's
  99054. // easier to handle this case. if(!global) { ...}
  99055. module.exports = g;
  99056. /***/ }),
  99057. /* 20 */
  99058. /***/ (function(module, exports) {
  99059. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99060. module.exports = CANNON;
  99061. /***/ }),
  99062. /* 21 */
  99063. /***/ (function(module, exports) {
  99064. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99065. module.exports = OIMO;
  99066. /***/ }),
  99067. /* 22 */
  99068. /***/ (function(module, exports) {
  99069. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  99070. module.exports = earcut;
  99071. /***/ }),
  99072. /* 23 */
  99073. /***/ (function(module, exports, __webpack_require__) {
  99074. "use strict";
  99075. Object.defineProperty(exports, "__esModule", { value: true });
  99076. var babylonjs_1 = __webpack_require__(0);
  99077. var helper_1 = __webpack_require__(3);
  99078. /**
  99079. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  99080. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  99081. */
  99082. var TemplateManager = /** @class */ (function () {
  99083. function TemplateManager(containerElement) {
  99084. this.containerElement = containerElement;
  99085. this.templates = {};
  99086. this.onTemplateInit = new babylonjs_1.Observable();
  99087. this.onTemplateLoaded = new babylonjs_1.Observable();
  99088. this.onTemplateStateChange = new babylonjs_1.Observable();
  99089. this.onAllLoaded = new babylonjs_1.Observable();
  99090. this.onEventTriggered = new babylonjs_1.Observable();
  99091. this.eventManager = new eventManager_1.EventManager(this);
  99092. }
  99093. /**
  99094. * Initialize the template(s) for the viewer. Called bay the Viewer class
  99095. * @param templates the templates to be used to initialize the main template
  99096. */
  99097. TemplateManager.prototype.initTemplate = function (templates) {
  99098. var _this = this;
  99099. var internalInit = function (dependencyMap, name, parentTemplate) {
  99100. //init template
  99101. var template = _this.templates[name];
  99102. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  99103. return internalInit(dependencyMap[childName], childName, template);
  99104. });
  99105. // register the observers
  99106. //template.onLoaded.add(() => {
  99107. var addToParent = function () {
  99108. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  99109. template.appendTo(containingElement);
  99110. _this._checkLoadedState();
  99111. };
  99112. if (parentTemplate && !parentTemplate.parent) {
  99113. parentTemplate.onAppended.add(function () {
  99114. addToParent();
  99115. });
  99116. }
  99117. else {
  99118. addToParent();
  99119. }
  99120. //});
  99121. return template;
  99122. };
  99123. //build the html tree
  99124. return this._buildHTMLTree(templates).then(function (htmlTree) {
  99125. if (_this.templates['main']) {
  99126. internalInit(htmlTree, 'main');
  99127. }
  99128. else {
  99129. _this._checkLoadedState();
  99130. }
  99131. return;
  99132. });
  99133. };
  99134. /**
  99135. *
  99136. * This function will create a simple map with child-dependencies of the template html tree.
  99137. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  99138. * It is expected that the main template will be called main!
  99139. *
  99140. * @param templates
  99141. */
  99142. TemplateManager.prototype._buildHTMLTree = function (templates) {
  99143. var _this = this;
  99144. var promises = Object.keys(templates).map(function (name) {
  99145. // if the template was overridden
  99146. if (!templates[name])
  99147. return Promise.resolve(false);
  99148. // else - we have a template, let's do our job!
  99149. var template = new Template(name, templates[name]);
  99150. template.onLoaded.add(function () {
  99151. _this.onTemplateLoaded.notifyObservers(template);
  99152. });
  99153. template.onStateChange.add(function () {
  99154. _this.onTemplateStateChange.notifyObservers(template);
  99155. });
  99156. _this.onTemplateInit.notifyObservers(template);
  99157. // make sure the global onEventTriggered is called as well
  99158. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  99159. _this.templates[name] = template;
  99160. return template.initPromise;
  99161. });
  99162. return Promise.all(promises).then(function () {
  99163. var templateStructure = {};
  99164. // now iterate through all templates and check for children:
  99165. var buildTree = function (parentObject, name) {
  99166. _this.templates[name].isInHtmlTree = true;
  99167. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  99168. childNodes.forEach(function (element) {
  99169. parentObject[element] = {};
  99170. buildTree(parentObject[element], element);
  99171. });
  99172. };
  99173. if (_this.templates['main']) {
  99174. buildTree(templateStructure, "main");
  99175. }
  99176. return templateStructure;
  99177. });
  99178. };
  99179. /**
  99180. * Get the canvas in the template tree.
  99181. * There must be one and only one canvas inthe template.
  99182. */
  99183. TemplateManager.prototype.getCanvas = function () {
  99184. return this.containerElement.querySelector('canvas');
  99185. };
  99186. /**
  99187. * Get a specific template from the template tree
  99188. * @param name the name of the template to load
  99189. */
  99190. TemplateManager.prototype.getTemplate = function (name) {
  99191. return this.templates[name];
  99192. };
  99193. TemplateManager.prototype._checkLoadedState = function () {
  99194. var _this = this;
  99195. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  99196. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  99197. });
  99198. if (done) {
  99199. this.onAllLoaded.notifyObservers(this);
  99200. }
  99201. };
  99202. /**
  99203. * Dispose the template manager
  99204. */
  99205. TemplateManager.prototype.dispose = function () {
  99206. var _this = this;
  99207. // dispose all templates
  99208. Object.keys(this.templates).forEach(function (template) {
  99209. _this.templates[template].dispose();
  99210. });
  99211. this.templates = {};
  99212. this.eventManager.dispose();
  99213. this.onTemplateInit.clear();
  99214. this.onAllLoaded.clear();
  99215. this.onEventTriggered.clear();
  99216. this.onTemplateLoaded.clear();
  99217. this.onTemplateStateChange.clear();
  99218. };
  99219. return TemplateManager;
  99220. }());
  99221. exports.TemplateManager = TemplateManager;
  99222. var Handlebars = __webpack_require__(24);
  99223. var eventManager_1 = __webpack_require__(25);
  99224. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  99225. Handlebars.registerHelper('eachInMap', function (map, block) {
  99226. var out = '';
  99227. Object.keys(map).map(function (prop) {
  99228. var data = map[prop];
  99229. if (typeof data === 'object') {
  99230. data.id = data.id || prop;
  99231. out += block.fn(data);
  99232. }
  99233. else {
  99234. out += block.fn({ id: prop, value: data });
  99235. }
  99236. });
  99237. return out;
  99238. });
  99239. /**
  99240. * This class represents a single template in the viewer's template tree.
  99241. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  99242. * A template is injected using the template manager in the correct position.
  99243. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  99244. *
  99245. * For further information please refer to the documentation page, https://doc.babylonjs.com
  99246. */
  99247. var Template = /** @class */ (function () {
  99248. function Template(name, _configuration) {
  99249. var _this = this;
  99250. this.name = name;
  99251. this._configuration = _configuration;
  99252. this.onLoaded = new babylonjs_1.Observable();
  99253. this.onAppended = new babylonjs_1.Observable();
  99254. this.onStateChange = new babylonjs_1.Observable();
  99255. this.onEventTriggered = new babylonjs_1.Observable();
  99256. this.loadRequests = [];
  99257. this.isLoaded = false;
  99258. this.isShown = false;
  99259. this.isInHtmlTree = false;
  99260. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  99261. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  99262. if (htmlTemplate) {
  99263. _this._htmlTemplate = htmlTemplate;
  99264. var compiledTemplate = Handlebars.compile(htmlTemplate);
  99265. var config = _this._configuration.params || {};
  99266. var rawHtml = compiledTemplate(config);
  99267. _this._fragment = document.createRange().createContextualFragment(rawHtml);
  99268. _this.isLoaded = true;
  99269. _this.isShown = true;
  99270. _this.onLoaded.notifyObservers(_this);
  99271. }
  99272. return _this;
  99273. });
  99274. }
  99275. /**
  99276. * Some templates have parameters (like background color for example).
  99277. * The parameters are provided to Handlebars which in turn generates the template.
  99278. * This function will update the template with the new parameters
  99279. *
  99280. * @param params the new template parameters
  99281. */
  99282. Template.prototype.updateParams = function (params) {
  99283. this._configuration.params = params;
  99284. // update the template
  99285. if (this.isLoaded) {
  99286. this.dispose();
  99287. }
  99288. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  99289. var config = this._configuration.params || {};
  99290. var rawHtml = compiledTemplate(config);
  99291. this._fragment = document.createRange().createContextualFragment(rawHtml);
  99292. if (this.parent) {
  99293. this.appendTo(this.parent, true);
  99294. }
  99295. };
  99296. Object.defineProperty(Template.prototype, "configuration", {
  99297. /**
  99298. * Get the template'S configuration
  99299. */
  99300. get: function () {
  99301. return this._configuration;
  99302. },
  99303. enumerable: true,
  99304. configurable: true
  99305. });
  99306. /**
  99307. * A template can be a parent element for other templates or HTML elements.
  99308. * This function will deliver all child HTML elements of this template.
  99309. */
  99310. Template.prototype.getChildElements = function () {
  99311. var childrenArray = [];
  99312. //Edge and IE don't support frage,ent.children
  99313. var children = this._fragment.children;
  99314. if (!children) {
  99315. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  99316. children = this._fragment.querySelectorAll('*');
  99317. }
  99318. for (var i = 0; i < children.length; ++i) {
  99319. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  99320. }
  99321. return childrenArray;
  99322. };
  99323. /**
  99324. * Appending the template to a parent HTML element.
  99325. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  99326. * @param parent the parent to which the template is added
  99327. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  99328. */
  99329. Template.prototype.appendTo = function (parent, forceRemove) {
  99330. var _this = this;
  99331. if (this.parent) {
  99332. if (forceRemove) {
  99333. this.parent.removeChild(this._fragment);
  99334. }
  99335. else {
  99336. return;
  99337. }
  99338. }
  99339. this.parent = parent;
  99340. if (this._configuration.id) {
  99341. this.parent.id = this._configuration.id;
  99342. }
  99343. this._fragment = this.parent.appendChild(this._fragment);
  99344. // appended only one frame after.
  99345. setTimeout(function () {
  99346. _this._registerEvents();
  99347. _this.onAppended.notifyObservers(_this);
  99348. });
  99349. };
  99350. /**
  99351. * Show the template using the provided visibilityFunction, or natively using display: flex.
  99352. * The provided function returns a promise that should be fullfilled when the element is shown.
  99353. * Since it is a promise async operations are more than possible.
  99354. * See the default viewer for an opacity example.
  99355. * @param visibilityFunction The function to execute to show the template.
  99356. */
  99357. Template.prototype.show = function (visibilityFunction) {
  99358. var _this = this;
  99359. if (this._isHiding)
  99360. return Promise.resolve(this);
  99361. return Promise.resolve().then(function () {
  99362. _this._isShowing = true;
  99363. if (visibilityFunction) {
  99364. return visibilityFunction(_this);
  99365. }
  99366. else {
  99367. // flex? box? should this be configurable easier than the visibilityFunction?
  99368. _this.parent.style.display = 'flex';
  99369. return _this;
  99370. }
  99371. }).then(function () {
  99372. _this.isShown = true;
  99373. _this._isShowing = false;
  99374. _this.onStateChange.notifyObservers(_this);
  99375. return _this;
  99376. });
  99377. };
  99378. /**
  99379. * Hide the template using the provided visibilityFunction, or natively using display: none.
  99380. * The provided function returns a promise that should be fullfilled when the element is hidden.
  99381. * Since it is a promise async operations are more than possible.
  99382. * See the default viewer for an opacity example.
  99383. * @param visibilityFunction The function to execute to show the template.
  99384. */
  99385. Template.prototype.hide = function (visibilityFunction) {
  99386. var _this = this;
  99387. if (this._isShowing)
  99388. return Promise.resolve(this);
  99389. return Promise.resolve().then(function () {
  99390. _this._isHiding = true;
  99391. if (visibilityFunction) {
  99392. return visibilityFunction(_this);
  99393. }
  99394. else {
  99395. // flex? box? should this be configurable easier than the visibilityFunction?
  99396. _this.parent.style.display = 'hide';
  99397. return _this;
  99398. }
  99399. }).then(function () {
  99400. _this.isShown = false;
  99401. _this._isHiding = false;
  99402. _this.onStateChange.notifyObservers(_this);
  99403. return _this;
  99404. });
  99405. };
  99406. /**
  99407. * Dispose this template
  99408. */
  99409. Template.prototype.dispose = function () {
  99410. this.onAppended.clear();
  99411. this.onEventTriggered.clear();
  99412. this.onLoaded.clear();
  99413. this.onStateChange.clear();
  99414. this.isLoaded = false;
  99415. // remove from parent
  99416. try {
  99417. this.parent.removeChild(this._fragment);
  99418. }
  99419. catch (e) {
  99420. //noop
  99421. }
  99422. this.loadRequests.forEach(function (request) {
  99423. request.abort();
  99424. });
  99425. if (this._registeredEvents) {
  99426. this._registeredEvents.forEach(function (evt) {
  99427. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  99428. });
  99429. }
  99430. delete this._fragment;
  99431. };
  99432. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  99433. var _this = this;
  99434. if (!templateConfig) {
  99435. return Promise.reject('No templateConfig provided');
  99436. }
  99437. else if (templateConfig.html !== undefined) {
  99438. return Promise.resolve(templateConfig.html);
  99439. }
  99440. else {
  99441. var location_1 = this._getTemplateLocation(templateConfig);
  99442. if (helper_1.isUrl(location_1)) {
  99443. return new Promise(function (resolve, reject) {
  99444. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  99445. resolve(data);
  99446. }, undefined, undefined, false, function (request, error) {
  99447. reject(error);
  99448. });
  99449. _this.loadRequests.push(fileRequest);
  99450. });
  99451. }
  99452. else {
  99453. location_1 = location_1.replace('#', '');
  99454. var element = document.getElementById(location_1);
  99455. if (element) {
  99456. return Promise.resolve(element.innerHTML);
  99457. }
  99458. else {
  99459. return Promise.reject('Template ID not found');
  99460. }
  99461. }
  99462. }
  99463. };
  99464. Template.prototype._registerEvents = function () {
  99465. var _this = this;
  99466. this._registeredEvents = this._registeredEvents || [];
  99467. if (this._registeredEvents.length) {
  99468. // first remove the registered events
  99469. this._registeredEvents.forEach(function (evt) {
  99470. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  99471. });
  99472. }
  99473. if (this._configuration.events) {
  99474. var _loop_1 = function (eventName) {
  99475. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  99476. var functionToFire_1 = function (selector, event) {
  99477. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  99478. };
  99479. // if boolean, set the parent as the event listener
  99480. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  99481. var binding = functionToFire_1.bind(this_1, '#' + this_1.parent.id);
  99482. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  99483. this_1._registeredEvents.push({
  99484. htmlElement: this_1.parent,
  99485. eventName: eventName,
  99486. function: binding
  99487. });
  99488. }
  99489. else if (typeof this_1._configuration.events[eventName] === 'object') {
  99490. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  99491. // strict null checl is working incorrectly, must override:
  99492. var event_1 = this_1._configuration.events[eventName] || {};
  99493. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  99494. if (selector && selector.indexOf('#') !== 0) {
  99495. selector = '#' + selector;
  99496. }
  99497. var htmlElement = _this.parent.querySelector(selector);
  99498. if (htmlElement) {
  99499. var binding = functionToFire_1.bind(_this, selector);
  99500. htmlElement.addEventListener(eventName, binding, false);
  99501. _this._registeredEvents.push({
  99502. htmlElement: htmlElement,
  99503. eventName: eventName,
  99504. function: binding
  99505. });
  99506. }
  99507. });
  99508. }
  99509. }
  99510. };
  99511. var this_1 = this;
  99512. for (var eventName in this._configuration.events) {
  99513. _loop_1(eventName);
  99514. }
  99515. }
  99516. };
  99517. Template.prototype._getTemplateLocation = function (templateConfig) {
  99518. if (!templateConfig || typeof templateConfig === 'string') {
  99519. return templateConfig;
  99520. }
  99521. else {
  99522. return templateConfig.location;
  99523. }
  99524. };
  99525. return Template;
  99526. }());
  99527. exports.Template = Template;
  99528. /***/ }),
  99529. /* 24 */
  99530. /***/ (function(module, exports, __webpack_require__) {
  99531. /**!
  99532. @license
  99533. handlebars v4.0.11
  99534. Copyright (C) 2011-2017 by Yehuda Katz
  99535. Permission is hereby granted, free of charge, to any person obtaining a copy
  99536. of this software and associated documentation files (the "Software"), to deal
  99537. in the Software without restriction, including without limitation the rights
  99538. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  99539. copies of the Software, and to permit persons to whom the Software is
  99540. furnished to do so, subject to the following conditions:
  99541. The above copyright notice and this permission notice shall be included in
  99542. all copies or substantial portions of the Software.
  99543. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  99544. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  99545. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  99546. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  99547. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  99548. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  99549. THE SOFTWARE.
  99550. */
  99551. !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],
  99552. 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){
  99553. 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"]}])});
  99554. /***/ }),
  99555. /* 25 */
  99556. /***/ (function(module, exports, __webpack_require__) {
  99557. "use strict";
  99558. Object.defineProperty(exports, "__esModule", { value: true });
  99559. /**
  99560. * The EventManager is in charge of registering user interctions with the viewer.
  99561. * It is used in the TemplateManager
  99562. */
  99563. var EventManager = /** @class */ (function () {
  99564. function EventManager(_templateManager) {
  99565. var _this = this;
  99566. this._templateManager = _templateManager;
  99567. this._callbacksContainer = {};
  99568. this._templateManager.onEventTriggered.add(function (eventData) {
  99569. _this._eventTriggered(eventData);
  99570. });
  99571. }
  99572. /**
  99573. * Register a new callback to a specific template.
  99574. * The best example for the usage can be found in the DefaultViewer
  99575. *
  99576. * @param templateName the templateName to register the event to
  99577. * @param callback The callback to be executed
  99578. * @param eventType the type of event to register
  99579. * @param selector an optional selector. if not defined the parent object in the template will be selected
  99580. */
  99581. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  99582. if (!this._callbacksContainer[templateName]) {
  99583. this._callbacksContainer[templateName] = [];
  99584. }
  99585. this._callbacksContainer[templateName].push({
  99586. eventType: eventType,
  99587. callback: callback
  99588. });
  99589. };
  99590. /**
  99591. * This will remove a registered event from the defined template.
  99592. * Each one of the variables apart from the template name are optional, but one must be provided.
  99593. *
  99594. * @param templateName the templateName
  99595. * @param callback the callback to remove (optional)
  99596. * @param eventType the event type to remove (optional)
  99597. * @param selector the selector from which to remove the event (optional)
  99598. */
  99599. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  99600. var callbackDefs = this._callbacksContainer[templateName] || [];
  99601. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  99602. };
  99603. EventManager.prototype._eventTriggered = function (data) {
  99604. var templateName = data.template.name;
  99605. var eventType = data.event.type;
  99606. var selector = data.selector;
  99607. var callbackDefs = this._callbacksContainer[templateName] || [];
  99608. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  99609. callbackDef.callback(data);
  99610. });
  99611. };
  99612. /**
  99613. * Dispose the event manager
  99614. */
  99615. EventManager.prototype.dispose = function () {
  99616. this._callbacksContainer = {};
  99617. };
  99618. return EventManager;
  99619. }());
  99620. exports.EventManager = EventManager;
  99621. /***/ }),
  99622. /* 26 */
  99623. /***/ (function(module, exports, __webpack_require__) {
  99624. "use strict";
  99625. Object.defineProperty(exports, "__esModule", { value: true });
  99626. var mappers_1 = __webpack_require__(1);
  99627. var types_1 = __webpack_require__(27);
  99628. var deepmerge = __webpack_require__(2);
  99629. var babylonjs_1 = __webpack_require__(0);
  99630. /**
  99631. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  99632. * parse the object and return a conform ViewerConfiguration.
  99633. * It is a private member of the scene.
  99634. */
  99635. var ConfigurationLoader = /** @class */ (function () {
  99636. function ConfigurationLoader(_enableCache) {
  99637. if (_enableCache === void 0) { _enableCache = false; }
  99638. this._enableCache = _enableCache;
  99639. this._configurationCache = {};
  99640. this._loadRequests = [];
  99641. }
  99642. /**
  99643. * load a configuration object that is defined in the initial configuration provided.
  99644. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  99645. *
  99646. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  99647. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  99648. * @returns A promise that delivers the extended viewer configuration, when done.
  99649. */
  99650. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  99651. var _this = this;
  99652. if (initConfig === void 0) { initConfig = {}; }
  99653. var loadedConfig = deepmerge({}, initConfig);
  99654. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  99655. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  99656. if (loadedConfig.configuration) {
  99657. var mapperType_1 = "json";
  99658. return Promise.resolve().then(function () {
  99659. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  99660. // a file to load
  99661. var url = '';
  99662. if (typeof loadedConfig.configuration === "string") {
  99663. url = loadedConfig.configuration;
  99664. }
  99665. // if configuration is an object
  99666. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  99667. url = loadedConfig.configuration.url;
  99668. var type = loadedConfig.configuration.mapper;
  99669. // empty string?
  99670. if (!type) {
  99671. // load mapper type from filename / url
  99672. type = loadedConfig.configuration.url.split('.').pop();
  99673. }
  99674. mapperType_1 = type || mapperType_1;
  99675. }
  99676. return _this._loadFile(url);
  99677. }
  99678. else {
  99679. if (typeof loadedConfig.configuration === "object") {
  99680. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  99681. return loadedConfig.configuration.payload || {};
  99682. }
  99683. return {};
  99684. }
  99685. }).then(function (data) {
  99686. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  99687. var parsed = mapper.map(data);
  99688. var merged = deepmerge(loadedConfig, parsed);
  99689. if (callback)
  99690. callback(merged);
  99691. return merged;
  99692. });
  99693. }
  99694. else {
  99695. if (callback)
  99696. callback(loadedConfig);
  99697. return Promise.resolve(loadedConfig);
  99698. }
  99699. };
  99700. /**
  99701. * Dispose the configuration loader. This will cancel file requests, if active.
  99702. */
  99703. ConfigurationLoader.prototype.dispose = function () {
  99704. this._loadRequests.forEach(function (request) {
  99705. request.abort();
  99706. });
  99707. this._loadRequests.length = 0;
  99708. };
  99709. ConfigurationLoader.prototype._loadFile = function (url) {
  99710. var _this = this;
  99711. var cacheReference = this._configurationCache;
  99712. if (this._enableCache && cacheReference[url]) {
  99713. return Promise.resolve(cacheReference[url]);
  99714. }
  99715. return new Promise(function (resolve, reject) {
  99716. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  99717. var idx = _this._loadRequests.indexOf(fileRequest);
  99718. if (idx !== -1)
  99719. _this._loadRequests.splice(idx, 1);
  99720. if (_this._enableCache)
  99721. cacheReference[url] = result;
  99722. resolve(result);
  99723. }, undefined, undefined, false, function (request, error) {
  99724. var idx = _this._loadRequests.indexOf(fileRequest);
  99725. if (idx !== -1)
  99726. _this._loadRequests.splice(idx, 1);
  99727. reject(error);
  99728. });
  99729. _this._loadRequests.push(fileRequest);
  99730. });
  99731. };
  99732. return ConfigurationLoader;
  99733. }());
  99734. exports.ConfigurationLoader = ConfigurationLoader;
  99735. /***/ }),
  99736. /* 27 */
  99737. /***/ (function(module, exports, __webpack_require__) {
  99738. "use strict";
  99739. Object.defineProperty(exports, "__esModule", { value: true });
  99740. var minimal_1 = __webpack_require__(28);
  99741. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  99742. var default_1 = __webpack_require__(29);
  99743. exports.defaultConfiguration = default_1.defaultConfiguration;
  99744. var getConfigurationType = function (type) {
  99745. switch (type) {
  99746. case 'default':
  99747. return default_1.defaultConfiguration;
  99748. case 'minimal':
  99749. return minimal_1.minimalConfiguration;
  99750. case 'none':
  99751. return {};
  99752. default:
  99753. return default_1.defaultConfiguration;
  99754. }
  99755. };
  99756. exports.getConfigurationType = getConfigurationType;
  99757. /***/ }),
  99758. /* 28 */
  99759. /***/ (function(module, exports, __webpack_require__) {
  99760. "use strict";
  99761. Object.defineProperty(exports, "__esModule", { value: true });
  99762. exports.minimalConfiguration = {
  99763. version: "0.1",
  99764. templates: {
  99765. main: {
  99766. html: __webpack_require__(7)
  99767. },
  99768. loadingScreen: {
  99769. html: __webpack_require__(8),
  99770. params: {
  99771. backgroundColor: "#000000",
  99772. 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"
  99773. }
  99774. },
  99775. viewer: {
  99776. html: __webpack_require__(10),
  99777. },
  99778. overlay: {
  99779. html: __webpack_require__(11),
  99780. params: {
  99781. closeImage: __webpack_require__(12),
  99782. closeText: 'Close'
  99783. }
  99784. },
  99785. error: {
  99786. html: __webpack_require__(13)
  99787. }
  99788. },
  99789. engine: {
  99790. antialiasing: true
  99791. }
  99792. };
  99793. /***/ }),
  99794. /* 29 */
  99795. /***/ (function(module, exports, __webpack_require__) {
  99796. "use strict";
  99797. Object.defineProperty(exports, "__esModule", { value: true });
  99798. exports.defaultConfiguration = {
  99799. version: "3.2.0-alpha4",
  99800. templates: {
  99801. main: {
  99802. html: __webpack_require__(7)
  99803. },
  99804. loadingScreen: {
  99805. html: __webpack_require__(8),
  99806. params: {
  99807. backgroundColor: "#000000",
  99808. loadingImage: __webpack_require__(9)
  99809. }
  99810. },
  99811. viewer: {
  99812. html: __webpack_require__(10),
  99813. events: {
  99814. pointerout: true,
  99815. pointerdown: true,
  99816. pointerup: true
  99817. }
  99818. },
  99819. navBar: {
  99820. html: __webpack_require__(30),
  99821. params: {
  99822. buttons: {
  99823. /*"help-button": {
  99824. altText: "Help",
  99825. image: require('../../../assets/img/help-circle.png')
  99826. },*/
  99827. "fullscreen-button": {
  99828. altText: "Fullscreen",
  99829. image: __webpack_require__(31)
  99830. }
  99831. },
  99832. visibilityTimeout: 2000
  99833. },
  99834. events: {
  99835. pointerdown: { 'fullscreen-button': true /*, '#help-button': true*/ },
  99836. pointerover: true
  99837. }
  99838. },
  99839. overlay: {
  99840. html: __webpack_require__(11),
  99841. params: {
  99842. closeImage: __webpack_require__(12),
  99843. closeText: 'Close'
  99844. }
  99845. },
  99846. help: {
  99847. html: __webpack_require__(32)
  99848. },
  99849. share: {
  99850. html: __webpack_require__(33)
  99851. },
  99852. error: {
  99853. html: __webpack_require__(13)
  99854. }
  99855. },
  99856. camera: {
  99857. behaviors: {
  99858. autoRotate: 0,
  99859. framing: {
  99860. type: 2,
  99861. zoomOnBoundingInfo: true,
  99862. zoomStopsAnimation: false
  99863. }
  99864. }
  99865. },
  99866. /*lights: {
  99867. "default": {
  99868. type: 1,
  99869. shadowEnabled: true,
  99870. direction: { x: -0.2, y: -0.8, z: 0 },
  99871. position: { x: 10, y: 10, z: 0 },
  99872. intensity: 4.5,
  99873. shadowConfig: {
  99874. useBlurExponentialShadowMap: true,
  99875. useKernelBlur: true,
  99876. blurKernel: 64,
  99877. blurScale: 4
  99878. }
  99879. }
  99880. },*/
  99881. skybox: {
  99882. /*cubeTexture: {
  99883. url: 'https://playground.babylonjs.com/textures/environment.dds',
  99884. gammaSpace: false
  99885. },*/
  99886. pbr: true,
  99887. blur: 0.7,
  99888. infiniteDIstance: false,
  99889. },
  99890. ground: true,
  99891. engine: {
  99892. antialiasing: true
  99893. },
  99894. scene: {
  99895. imageProcessingConfiguration: {
  99896. exposure: 1.4,
  99897. contrast: 1.66,
  99898. toneMappingEnabled: true
  99899. }
  99900. }
  99901. };
  99902. /***/ }),
  99903. /* 30 */
  99904. /***/ (function(module, exports) {
  99905. 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>";
  99906. /***/ }),
  99907. /* 31 */
  99908. /***/ (function(module, exports) {
  99909. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  99910. /***/ }),
  99911. /* 32 */
  99912. /***/ (function(module, exports) {
  99913. module.exports = "HELP";
  99914. /***/ }),
  99915. /* 33 */
  99916. /***/ (function(module, exports) {
  99917. module.exports = "SHARE";
  99918. /***/ }),
  99919. /* 34 */
  99920. /***/ (function(module, exports, __webpack_require__) {
  99921. (function universalModuleDefinition(root, factory) {
  99922. var amdDependencies = [];
  99923. var BABYLON = root.BABYLON || this.BABYLON;
  99924. if(true) {
  99925. BABYLON = BABYLON || __webpack_require__(0);
  99926. module.exports = factory(BABYLON);
  99927. } else if(typeof define === 'function' && define.amd) {
  99928. amdDependencies.push("babylonjs");
  99929. define("babylonjs-loaders", amdDependencies, factory);
  99930. } else if(typeof exports === 'object') {
  99931. BABYLON = BABYLON || require("babylonjs");
  99932. exports["babylonjs-loaders"] = factory(BABYLON);
  99933. } else {
  99934. root["BABYLON"] = factory(BABYLON);
  99935. }
  99936. })(this, function(BABYLON) {
  99937. BABYLON = BABYLON || this.BABYLON;
  99938. 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};
  99939. 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)}}();
  99940. var BABYLON;
  99941. (function (BABYLON) {
  99942. var STLFileLoader = /** @class */ (function () {
  99943. function STLFileLoader() {
  99944. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  99945. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  99946. 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;
  99947. 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;
  99948. this.name = "stl";
  99949. // force data to come in as an ArrayBuffer
  99950. // we'll convert to string if it looks like it's an ASCII .stl
  99951. this.extensions = {
  99952. ".stl": { isBinary: true },
  99953. };
  99954. }
  99955. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  99956. var matches;
  99957. if (this.isBinary(data)) {
  99958. // binary .stl
  99959. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  99960. this.parseBinary(babylonMesh, data);
  99961. if (meshes) {
  99962. meshes.push(babylonMesh);
  99963. }
  99964. return true;
  99965. }
  99966. // ASCII .stl
  99967. // convert to string
  99968. var array_buffer = new Uint8Array(data);
  99969. var str = '';
  99970. for (var i = 0; i < data.byteLength; i++) {
  99971. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  99972. }
  99973. data = str;
  99974. while (matches = this.solidPattern.exec(data)) {
  99975. var meshName = matches[1];
  99976. var meshNameFromEnd = matches[3];
  99977. if (meshName != meshNameFromEnd) {
  99978. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  99979. return false;
  99980. }
  99981. // check meshesNames
  99982. if (meshesNames && meshName) {
  99983. if (meshesNames instanceof Array) {
  99984. if (!meshesNames.indexOf(meshName)) {
  99985. continue;
  99986. }
  99987. }
  99988. else {
  99989. if (meshName !== meshesNames) {
  99990. continue;
  99991. }
  99992. }
  99993. }
  99994. // stl mesh name can be empty as well
  99995. meshName = meshName || "stlmesh";
  99996. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  99997. this.parseASCII(babylonMesh, matches[2]);
  99998. if (meshes) {
  99999. meshes.push(babylonMesh);
  100000. }
  100001. }
  100002. return true;
  100003. };
  100004. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100005. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100006. if (result) {
  100007. scene.createDefaultCameraOrLight();
  100008. }
  100009. return result;
  100010. };
  100011. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100012. var container = new BABYLON.AssetContainer(scene);
  100013. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100014. container.removeAllFromScene();
  100015. return container;
  100016. };
  100017. STLFileLoader.prototype.isBinary = function (data) {
  100018. // check if file size is correct for binary stl
  100019. var faceSize, nFaces, reader;
  100020. reader = new DataView(data);
  100021. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100022. nFaces = reader.getUint32(80, true);
  100023. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100024. return true;
  100025. }
  100026. // check characters higher than ASCII to confirm binary
  100027. var fileLength = reader.byteLength;
  100028. for (var index = 0; index < fileLength; index++) {
  100029. if (reader.getUint8(index) > 127) {
  100030. return true;
  100031. }
  100032. }
  100033. return false;
  100034. };
  100035. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100036. var reader = new DataView(data);
  100037. var faces = reader.getUint32(80, true);
  100038. var dataOffset = 84;
  100039. var faceLength = 12 * 4 + 2;
  100040. var offset = 0;
  100041. var positions = new Float32Array(faces * 3 * 3);
  100042. var normals = new Float32Array(faces * 3 * 3);
  100043. var indices = new Uint32Array(faces * 3);
  100044. var indicesCount = 0;
  100045. for (var face = 0; face < faces; face++) {
  100046. var start = dataOffset + face * faceLength;
  100047. var normalX = reader.getFloat32(start, true);
  100048. var normalY = reader.getFloat32(start + 4, true);
  100049. var normalZ = reader.getFloat32(start + 8, true);
  100050. for (var i = 1; i <= 3; i++) {
  100051. var vertexstart = start + i * 12;
  100052. // ordering is intentional to match ascii import
  100053. positions[offset] = reader.getFloat32(vertexstart, true);
  100054. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100055. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100056. normals[offset] = normalX;
  100057. normals[offset + 2] = normalY;
  100058. normals[offset + 1] = normalZ;
  100059. offset += 3;
  100060. }
  100061. indices[indicesCount] = indicesCount++;
  100062. indices[indicesCount] = indicesCount++;
  100063. indices[indicesCount] = indicesCount++;
  100064. }
  100065. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100066. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100067. mesh.setIndices(indices);
  100068. mesh.computeWorldMatrix(true);
  100069. };
  100070. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  100071. var positions = [];
  100072. var normals = [];
  100073. var indices = [];
  100074. var indicesCount = 0;
  100075. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  100076. var matches;
  100077. while (matches = this.facetsPattern.exec(solidData)) {
  100078. var facet = matches[1];
  100079. //one normal per face
  100080. var normalMatches = this.normalPattern.exec(facet);
  100081. this.normalPattern.lastIndex = 0;
  100082. if (!normalMatches) {
  100083. continue;
  100084. }
  100085. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  100086. var vertexMatch;
  100087. while (vertexMatch = this.vertexPattern.exec(facet)) {
  100088. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  100089. normals.push(normal[0], normal[1], normal[2]);
  100090. }
  100091. indices.push(indicesCount++, indicesCount++, indicesCount++);
  100092. this.vertexPattern.lastIndex = 0;
  100093. }
  100094. this.facetsPattern.lastIndex = 0;
  100095. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100096. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100097. mesh.setIndices(indices);
  100098. mesh.computeWorldMatrix(true);
  100099. };
  100100. return STLFileLoader;
  100101. }());
  100102. BABYLON.STLFileLoader = STLFileLoader;
  100103. if (BABYLON.SceneLoader) {
  100104. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  100105. }
  100106. })(BABYLON || (BABYLON = {}));
  100107. //# sourceMappingURL=babylon.stlFileLoader.js.map
  100108. var BABYLON;
  100109. (function (BABYLON) {
  100110. /**
  100111. * Class reading and parsing the MTL file bundled with the obj file.
  100112. */
  100113. var MTLFileLoader = /** @class */ (function () {
  100114. function MTLFileLoader() {
  100115. // All material loaded from the mtl will be set here
  100116. this.materials = [];
  100117. }
  100118. /**
  100119. * This function will read the mtl file and create each material described inside
  100120. * This function could be improve by adding :
  100121. * -some component missing (Ni, Tf...)
  100122. * -including the specific options available
  100123. *
  100124. * @param scene
  100125. * @param data
  100126. * @param rootUrl
  100127. */
  100128. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  100129. if (data instanceof ArrayBuffer) {
  100130. return;
  100131. }
  100132. //Split the lines from the file
  100133. var lines = data.split('\n');
  100134. //Space char
  100135. var delimiter_pattern = /\s+/;
  100136. //Array with RGB colors
  100137. var color;
  100138. //New material
  100139. var material = null;
  100140. //Look at each line
  100141. for (var i = 0; i < lines.length; i++) {
  100142. var line = lines[i].trim();
  100143. // Blank line or comment
  100144. if (line.length === 0 || line.charAt(0) === '#') {
  100145. continue;
  100146. }
  100147. //Get the first parameter (keyword)
  100148. var pos = line.indexOf(' ');
  100149. var key = (pos >= 0) ? line.substring(0, pos) : line;
  100150. key = key.toLowerCase();
  100151. //Get the data following the key
  100152. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  100153. //This mtl keyword will create the new material
  100154. if (key === "newmtl") {
  100155. //Check if it is the first material.
  100156. // Materials specifications are described after this keyword.
  100157. if (material) {
  100158. //Add the previous material in the material array.
  100159. this.materials.push(material);
  100160. }
  100161. //Create a new material.
  100162. // value is the name of the material read in the mtl file
  100163. material = new BABYLON.StandardMaterial(value, scene);
  100164. }
  100165. else if (key === "kd" && material) {
  100166. // Diffuse color (color under white light) using RGB values
  100167. //value = "r g b"
  100168. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100169. //color = [r,g,b]
  100170. //Set tghe color into the material
  100171. material.diffuseColor = BABYLON.Color3.FromArray(color);
  100172. }
  100173. else if (key === "ka" && material) {
  100174. // Ambient color (color under shadow) using RGB values
  100175. //value = "r g b"
  100176. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100177. //color = [r,g,b]
  100178. //Set tghe color into the material
  100179. material.ambientColor = BABYLON.Color3.FromArray(color);
  100180. }
  100181. else if (key === "ks" && material) {
  100182. // Specular color (color when light is reflected from shiny surface) using RGB values
  100183. //value = "r g b"
  100184. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100185. //color = [r,g,b]
  100186. //Set the color into the material
  100187. material.specularColor = BABYLON.Color3.FromArray(color);
  100188. }
  100189. else if (key === "ke" && material) {
  100190. // Emissive color using RGB values
  100191. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100192. material.emissiveColor = BABYLON.Color3.FromArray(color);
  100193. }
  100194. else if (key === "ns" && material) {
  100195. //value = "Integer"
  100196. material.specularPower = parseFloat(value);
  100197. }
  100198. else if (key === "d" && material) {
  100199. //d is dissolve for current material. It mean alpha for BABYLON
  100200. material.alpha = parseFloat(value);
  100201. //Texture
  100202. //This part can be improved by adding the possible options of texture
  100203. }
  100204. else if (key === "map_ka" && material) {
  100205. // ambient texture map with a loaded image
  100206. //We must first get the folder of the image
  100207. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100208. }
  100209. else if (key === "map_kd" && material) {
  100210. // Diffuse texture map with a loaded image
  100211. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100212. }
  100213. else if (key === "map_ks" && material) {
  100214. // Specular texture map with a loaded image
  100215. //We must first get the folder of the image
  100216. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100217. }
  100218. else if (key === "map_ns") {
  100219. //Specular
  100220. //Specular highlight component
  100221. //We must first get the folder of the image
  100222. //
  100223. //Not supported by BABYLON
  100224. //
  100225. // continue;
  100226. }
  100227. else if (key === "map_bump" && material) {
  100228. //The bump texture
  100229. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100230. }
  100231. else if (key === "map_d" && material) {
  100232. // The dissolve of the material
  100233. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100234. //Options for illumination
  100235. }
  100236. else if (key === "illum") {
  100237. //Illumination
  100238. if (value === "0") {
  100239. //That mean Kd == Kd
  100240. }
  100241. else if (value === "1") {
  100242. //Color on and Ambient on
  100243. }
  100244. else if (value === "2") {
  100245. //Highlight on
  100246. }
  100247. else if (value === "3") {
  100248. //Reflection on and Ray trace on
  100249. }
  100250. else if (value === "4") {
  100251. //Transparency: Glass on, Reflection: Ray trace on
  100252. }
  100253. else if (value === "5") {
  100254. //Reflection: Fresnel on and Ray trace on
  100255. }
  100256. else if (value === "6") {
  100257. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  100258. }
  100259. else if (value === "7") {
  100260. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  100261. }
  100262. else if (value === "8") {
  100263. //Reflection on and Ray trace off
  100264. }
  100265. else if (value === "9") {
  100266. //Transparency: Glass on, Reflection: Ray trace off
  100267. }
  100268. else if (value === "10") {
  100269. //Casts shadows onto invisible surfaces
  100270. }
  100271. }
  100272. else {
  100273. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  100274. }
  100275. }
  100276. //At the end of the file, add the last material
  100277. if (material) {
  100278. this.materials.push(material);
  100279. }
  100280. };
  100281. /**
  100282. * Gets the texture for the material.
  100283. *
  100284. * If the material is imported from input file,
  100285. * We sanitize the url to ensure it takes the textre from aside the material.
  100286. *
  100287. * @param rootUrl The root url to load from
  100288. * @param value The value stored in the mtl
  100289. * @return The Texture
  100290. */
  100291. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  100292. if (!value) {
  100293. return null;
  100294. }
  100295. var url = rootUrl;
  100296. // Load from input file.
  100297. if (rootUrl === "file:") {
  100298. var lastDelimiter = value.lastIndexOf("\\");
  100299. if (lastDelimiter === -1) {
  100300. lastDelimiter = value.lastIndexOf("/");
  100301. }
  100302. if (lastDelimiter > -1) {
  100303. url += value.substr(lastDelimiter + 1);
  100304. }
  100305. else {
  100306. url += value;
  100307. }
  100308. }
  100309. // Not from input file.
  100310. else {
  100311. url += value;
  100312. }
  100313. return new BABYLON.Texture(url, scene);
  100314. };
  100315. return MTLFileLoader;
  100316. }());
  100317. BABYLON.MTLFileLoader = MTLFileLoader;
  100318. var OBJFileLoader = /** @class */ (function () {
  100319. function OBJFileLoader() {
  100320. this.name = "obj";
  100321. this.extensions = ".obj";
  100322. this.obj = /^o/;
  100323. this.group = /^g/;
  100324. this.mtllib = /^mtllib /;
  100325. this.usemtl = /^usemtl /;
  100326. this.smooth = /^s /;
  100327. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100328. // vn float float float
  100329. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100330. // vt float float
  100331. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100332. // f vertex vertex vertex ...
  100333. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  100334. // f vertex/uvs vertex/uvs vertex/uvs ...
  100335. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100336. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  100337. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100338. // f vertex//normal vertex//normal vertex//normal ...
  100339. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  100340. }
  100341. /**
  100342. * Calls synchronously the MTL file attached to this obj.
  100343. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  100344. * Without this function materials are not displayed in the first frame (but displayed after).
  100345. * In consequence it is impossible to get material information in your HTML file
  100346. *
  100347. * @param url The URL of the MTL file
  100348. * @param rootUrl
  100349. * @param onSuccess Callback function to be called when the MTL file is loaded
  100350. * @private
  100351. */
  100352. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  100353. //The complete path to the mtl file
  100354. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  100355. // Loads through the babylon tools to allow fileInput search.
  100356. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  100357. };
  100358. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100359. //get the meshes from OBJ file
  100360. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  100361. //Push meshes from OBJ file into the variable mesh of this function
  100362. if (meshes) {
  100363. loadedMeshes.forEach(function (mesh) {
  100364. meshes.push(mesh);
  100365. });
  100366. }
  100367. return true;
  100368. };
  100369. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  100370. //Get the 3D model
  100371. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  100372. };
  100373. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100374. var container = new BABYLON.AssetContainer(scene);
  100375. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100376. container.removeAllFromScene();
  100377. return container;
  100378. };
  100379. /**
  100380. * Read the OBJ file and create an Array of meshes.
  100381. * Each mesh contains all information given by the OBJ and the MTL file.
  100382. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  100383. *
  100384. * @param meshesNames
  100385. * @param scene BABYLON.Scene The scene where are displayed the data
  100386. * @param data String The content of the obj file
  100387. * @param rootUrl String The path to the folder
  100388. * @returns Array<AbstractMesh>
  100389. * @private
  100390. */
  100391. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  100392. var positions = []; //values for the positions of vertices
  100393. var normals = []; //Values for the normals
  100394. var uvs = []; //Values for the textures
  100395. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  100396. var handledMesh; //The current mesh of meshes array
  100397. var indicesForBabylon = []; //The list of indices for VertexData
  100398. var wrappedPositionForBabylon = []; //The list of position in vectors
  100399. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  100400. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  100401. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  100402. var curPositionInIndices = 0;
  100403. var hasMeshes = false; //Meshes are defined in the file
  100404. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  100405. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  100406. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  100407. var triangles = []; //Indices from new triangles coming from polygons
  100408. var materialNameFromObj = ""; //The name of the current material
  100409. var fileToLoad = ""; //The name of the mtlFile to load
  100410. var materialsFromMTLFile = new MTLFileLoader();
  100411. var objMeshName = ""; //The name of the current obj mesh
  100412. var increment = 1; //Id for meshes created by the multimaterial
  100413. var isFirstMaterial = true;
  100414. /**
  100415. * Search for obj in the given array.
  100416. * This function is called to check if a couple of data already exists in an array.
  100417. *
  100418. * If found, returns the index of the founded tuple index. Returns -1 if not found
  100419. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  100420. * @param obj Array<number>
  100421. * @returns {boolean}
  100422. */
  100423. var isInArray = function (arr, obj) {
  100424. if (!arr[obj[0]])
  100425. arr[obj[0]] = { normals: [], idx: [] };
  100426. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100427. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  100428. };
  100429. var isInArrayUV = function (arr, obj) {
  100430. if (!arr[obj[0]])
  100431. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  100432. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  100433. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  100434. return arr[obj[0]].idx[idx];
  100435. }
  100436. return -1;
  100437. };
  100438. /**
  100439. * This function set the data for each triangle.
  100440. * Data are position, normals and uvs
  100441. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  100442. * If the tuple already exist, add only their indice
  100443. *
  100444. * @param indicePositionFromObj Integer The index in positions array
  100445. * @param indiceUvsFromObj Integer The index in uvs array
  100446. * @param indiceNormalFromObj Integer The index in normals array
  100447. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  100448. * @param textureVectorFromOBJ Vector3 The value of uvs
  100449. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  100450. */
  100451. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  100452. //Check if this tuple already exists in the list of tuples
  100453. var _index;
  100454. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  100455. _index = isInArrayUV(tuplePosNorm, [
  100456. indicePositionFromObj,
  100457. indiceNormalFromObj,
  100458. indiceUvsFromObj
  100459. ]);
  100460. }
  100461. else {
  100462. _index = isInArray(tuplePosNorm, [
  100463. indicePositionFromObj,
  100464. indiceNormalFromObj
  100465. ]);
  100466. }
  100467. //If it not exists
  100468. if (_index == -1) {
  100469. //Add an new indice.
  100470. //The array of indices is only an array with his length equal to the number of triangles - 1.
  100471. //We add vertices data in this order
  100472. indicesForBabylon.push(wrappedPositionForBabylon.length);
  100473. //Push the position of vertice for Babylon
  100474. //Each element is a BABYLON.Vector3(x,y,z)
  100475. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  100476. //Push the uvs for Babylon
  100477. //Each element is a BABYLON.Vector3(u,v)
  100478. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  100479. //Push the normals for Babylon
  100480. //Each element is a BABYLON.Vector3(x,y,z)
  100481. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  100482. //Add the tuple in the comparison list
  100483. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  100484. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  100485. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  100486. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  100487. }
  100488. else {
  100489. //The tuple already exists
  100490. //Add the index of the already existing tuple
  100491. //At this index we can get the value of position, normal and uvs of vertex
  100492. indicesForBabylon.push(_index);
  100493. }
  100494. };
  100495. /**
  100496. * Transform BABYLON.Vector() object onto 3 digits in an array
  100497. */
  100498. var unwrapData = function () {
  100499. //Every array has the same length
  100500. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  100501. //Push the x, y, z values of each element in the unwrapped array
  100502. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  100503. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  100504. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  100505. }
  100506. // Reset arrays for the next new meshes
  100507. wrappedPositionForBabylon = [];
  100508. wrappedNormalsForBabylon = [];
  100509. wrappedUvsForBabylon = [];
  100510. tuplePosNorm = [];
  100511. curPositionInIndices = 0;
  100512. };
  100513. /**
  100514. * Create triangles from polygons by recursion
  100515. * The best to understand how it works is to draw it in the same time you get the recursion.
  100516. * It is important to notice that a triangle is a polygon
  100517. * We get 4 patterns of face defined in OBJ File :
  100518. * facePattern1 = ["1","2","3","4","5","6"]
  100519. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  100520. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  100521. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  100522. * Each pattern is divided by the same method
  100523. * @param face Array[String] The indices of elements
  100524. * @param v Integer The variable to increment
  100525. */
  100526. var getTriangles = function (face, v) {
  100527. //Work for each element of the array
  100528. if (v + 1 < face.length) {
  100529. //Add on the triangle variable the indexes to obtain triangles
  100530. triangles.push(face[0], face[v], face[v + 1]);
  100531. //Incrementation for recursion
  100532. v += 1;
  100533. //Recursion
  100534. getTriangles(face, v);
  100535. }
  100536. //Result obtained after 2 iterations:
  100537. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  100538. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  100539. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  100540. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  100541. };
  100542. /**
  100543. * Create triangles and push the data for each polygon for the pattern 1
  100544. * In this pattern we get vertice positions
  100545. * @param face
  100546. * @param v
  100547. */
  100548. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  100549. //Get the indices of triangles for each polygon
  100550. getTriangles(face, v);
  100551. //For each element in the triangles array.
  100552. //This var could contains 1 to an infinity of triangles
  100553. for (var k = 0; k < triangles.length; k++) {
  100554. // Set position indice
  100555. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  100556. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  100557. positions[indicePositionFromObj], //Get the vectors data
  100558. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  100559. );
  100560. }
  100561. //Reset variable for the next line
  100562. triangles = [];
  100563. };
  100564. /**
  100565. * Create triangles and push the data for each polygon for the pattern 2
  100566. * In this pattern we get vertice positions and uvsu
  100567. * @param face
  100568. * @param v
  100569. */
  100570. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  100571. //Get the indices of triangles for each polygon
  100572. getTriangles(face, v);
  100573. for (var k = 0; k < triangles.length; k++) {
  100574. //triangle[k] = "1/1"
  100575. //Split the data for getting position and uv
  100576. var point = triangles[k].split("/"); // ["1", "1"]
  100577. //Set position indice
  100578. var indicePositionFromObj = parseInt(point[0]) - 1;
  100579. //Set uv indice
  100580. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100581. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  100582. positions[indicePositionFromObj], //Get the values for each element
  100583. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  100584. );
  100585. }
  100586. //Reset variable for the next line
  100587. triangles = [];
  100588. };
  100589. /**
  100590. * Create triangles and push the data for each polygon for the pattern 3
  100591. * In this pattern we get vertice positions, uvs and normals
  100592. * @param face
  100593. * @param v
  100594. */
  100595. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  100596. //Get the indices of triangles for each polygon
  100597. getTriangles(face, v);
  100598. for (var k = 0; k < triangles.length; k++) {
  100599. //triangle[k] = "1/1/1"
  100600. //Split the data for getting position, uv, and normals
  100601. var point = triangles[k].split("/"); // ["1", "1", "1"]
  100602. // Set position indice
  100603. var indicePositionFromObj = parseInt(point[0]) - 1;
  100604. // Set uv indice
  100605. var indiceUvsFromObj = parseInt(point[1]) - 1;
  100606. // Set normal indice
  100607. var indiceNormalFromObj = parseInt(point[2]) - 1;
  100608. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  100609. );
  100610. }
  100611. //Reset variable for the next line
  100612. triangles = [];
  100613. };
  100614. /**
  100615. * Create triangles and push the data for each polygon for the pattern 4
  100616. * In this pattern we get vertice positions and normals
  100617. * @param face
  100618. * @param v
  100619. */
  100620. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  100621. getTriangles(face, v);
  100622. for (var k = 0; k < triangles.length; k++) {
  100623. //triangle[k] = "1//1"
  100624. //Split the data for getting position and normals
  100625. var point = triangles[k].split("//"); // ["1", "1"]
  100626. // We check indices, and normals
  100627. var indicePositionFromObj = parseInt(point[0]) - 1;
  100628. var indiceNormalFromObj = parseInt(point[1]) - 1;
  100629. setData(indicePositionFromObj, 1, //Default value for uv
  100630. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  100631. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  100632. }
  100633. //Reset variable for the next line
  100634. triangles = [];
  100635. };
  100636. var addPreviousObjMesh = function () {
  100637. //Check if it is not the first mesh. Otherwise we don't have data.
  100638. if (meshesFromObj.length > 0) {
  100639. //Get the previous mesh for applying the data about the faces
  100640. //=> in obj file, faces definition append after the name of the mesh
  100641. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100642. //Set the data into Array for the mesh
  100643. unwrapData();
  100644. // Reverse tab. Otherwise face are displayed in the wrong sens
  100645. indicesForBabylon.reverse();
  100646. //Set the information for the mesh
  100647. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  100648. handledMesh.indices = indicesForBabylon.slice();
  100649. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  100650. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  100651. handledMesh.uvs = unwrappedUVForBabylon.slice();
  100652. //Reset the array for the next mesh
  100653. indicesForBabylon = [];
  100654. unwrappedPositionsForBabylon = [];
  100655. unwrappedNormalsForBabylon = [];
  100656. unwrappedUVForBabylon = [];
  100657. }
  100658. };
  100659. //Main function
  100660. //Split the file into lines
  100661. var lines = data.split('\n');
  100662. //Look at each line
  100663. for (var i = 0; i < lines.length; i++) {
  100664. var line = lines[i].trim();
  100665. var result;
  100666. //Comment or newLine
  100667. if (line.length === 0 || line.charAt(0) === '#') {
  100668. continue;
  100669. //Get information about one position possible for the vertices
  100670. }
  100671. else if ((result = this.vertexPattern.exec(line)) !== null) {
  100672. //Create a Vector3 with the position x, y, z
  100673. //Value of result:
  100674. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100675. //Add the Vector in the list of positions
  100676. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100677. }
  100678. else if ((result = this.normalPattern.exec(line)) !== null) {
  100679. //Create a Vector3 with the normals x, y, z
  100680. //Value of result
  100681. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  100682. //Add the Vector in the list of normals
  100683. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  100684. }
  100685. else if ((result = this.uvPattern.exec(line)) !== null) {
  100686. //Create a Vector2 with the normals u, v
  100687. //Value of result
  100688. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  100689. //Add the Vector in the list of uvs
  100690. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  100691. //Identify patterns of faces
  100692. //Face could be defined in different type of pattern
  100693. }
  100694. else if ((result = this.facePattern3.exec(line)) !== null) {
  100695. //Value of result:
  100696. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  100697. //Set the data for this face
  100698. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  100699. 1);
  100700. }
  100701. else if ((result = this.facePattern4.exec(line)) !== null) {
  100702. //Value of result:
  100703. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  100704. //Set the data for this face
  100705. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  100706. 1);
  100707. }
  100708. else if ((result = this.facePattern2.exec(line)) !== null) {
  100709. //Value of result:
  100710. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  100711. //Set the data for this face
  100712. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  100713. 1);
  100714. }
  100715. else if ((result = this.facePattern1.exec(line)) !== null) {
  100716. //Value of result
  100717. //["f 1 2 3", "1 2 3"...]
  100718. //Set the data for this face
  100719. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  100720. 1);
  100721. //Define a mesh or an object
  100722. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  100723. }
  100724. else if (this.group.test(line) || this.obj.test(line)) {
  100725. //Create a new mesh corresponding to the name of the group.
  100726. //Definition of the mesh
  100727. var objMesh =
  100728. //Set the name of the current obj mesh
  100729. {
  100730. name: line.substring(2).trim(),
  100731. indices: undefined,
  100732. positions: undefined,
  100733. normals: undefined,
  100734. uvs: undefined,
  100735. materialName: ""
  100736. };
  100737. addPreviousObjMesh();
  100738. //Push the last mesh created with only the name
  100739. meshesFromObj.push(objMesh);
  100740. //Set this variable to indicate that now meshesFromObj has objects defined inside
  100741. hasMeshes = true;
  100742. isFirstMaterial = true;
  100743. increment = 1;
  100744. //Keyword for applying a material
  100745. }
  100746. else if (this.usemtl.test(line)) {
  100747. //Get the name of the material
  100748. materialNameFromObj = line.substring(7).trim();
  100749. //If this new material is in the same mesh
  100750. if (!isFirstMaterial) {
  100751. //Set the data for the previous mesh
  100752. addPreviousObjMesh();
  100753. //Create a new mesh
  100754. var objMesh =
  100755. //Set the name of the current obj mesh
  100756. {
  100757. name: objMeshName + "_mm" + increment.toString(),
  100758. indices: undefined,
  100759. positions: undefined,
  100760. normals: undefined,
  100761. uvs: undefined,
  100762. materialName: materialNameFromObj
  100763. };
  100764. increment++;
  100765. //If meshes are already defined
  100766. meshesFromObj.push(objMesh);
  100767. }
  100768. //Set the material name if the previous line define a mesh
  100769. if (hasMeshes && isFirstMaterial) {
  100770. //Set the material name to the previous mesh (1 material per mesh)
  100771. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  100772. isFirstMaterial = false;
  100773. }
  100774. //Keyword for loading the mtl file
  100775. }
  100776. else if (this.mtllib.test(line)) {
  100777. //Get the name of mtl file
  100778. fileToLoad = line.substring(7).trim();
  100779. //Apply smoothing
  100780. }
  100781. else if (this.smooth.test(line)) {
  100782. // smooth shading => apply smoothing
  100783. //Toda y I don't know it work with babylon and with obj.
  100784. //With the obj file an integer is set
  100785. }
  100786. else {
  100787. //If there is another possibility
  100788. console.log("Unhandled expression at line : " + line);
  100789. }
  100790. }
  100791. //At the end of the file, add the last mesh into the meshesFromObj array
  100792. if (hasMeshes) {
  100793. //Set the data for the last mesh
  100794. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  100795. //Reverse indices for displaying faces in the good sens
  100796. indicesForBabylon.reverse();
  100797. //Get the good array
  100798. unwrapData();
  100799. //Set array
  100800. handledMesh.indices = indicesForBabylon;
  100801. handledMesh.positions = unwrappedPositionsForBabylon;
  100802. handledMesh.normals = unwrappedNormalsForBabylon;
  100803. handledMesh.uvs = unwrappedUVForBabylon;
  100804. }
  100805. //If any o or g keyword found, create a mesj with a random id
  100806. if (!hasMeshes) {
  100807. // reverse tab of indices
  100808. indicesForBabylon.reverse();
  100809. //Get positions normals uvs
  100810. unwrapData();
  100811. //Set data for one mesh
  100812. meshesFromObj.push({
  100813. name: BABYLON.Geometry.RandomId(),
  100814. indices: indicesForBabylon,
  100815. positions: unwrappedPositionsForBabylon,
  100816. normals: unwrappedNormalsForBabylon,
  100817. uvs: unwrappedUVForBabylon,
  100818. materialName: materialNameFromObj
  100819. });
  100820. }
  100821. //Create a BABYLON.Mesh list
  100822. var babylonMeshesArray = []; //The mesh for babylon
  100823. var materialToUse = new Array();
  100824. //Set data for each mesh
  100825. for (var j = 0; j < meshesFromObj.length; j++) {
  100826. //check meshesNames (stlFileLoader)
  100827. if (meshesNames && meshesFromObj[j].name) {
  100828. if (meshesNames instanceof Array) {
  100829. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  100830. continue;
  100831. }
  100832. }
  100833. else {
  100834. if (meshesFromObj[j].name !== meshesNames) {
  100835. continue;
  100836. }
  100837. }
  100838. }
  100839. //Get the current mesh
  100840. //Set the data with VertexBuffer for each mesh
  100841. handledMesh = meshesFromObj[j];
  100842. //Create a BABYLON.Mesh with the name of the obj mesh
  100843. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  100844. //Push the name of the material to an array
  100845. //This is indispensable for the importMesh function
  100846. materialToUse.push(meshesFromObj[j].materialName);
  100847. var vertexData = new BABYLON.VertexData(); //The container for the values
  100848. //Set the data for the babylonMesh
  100849. vertexData.positions = handledMesh.positions;
  100850. vertexData.normals = handledMesh.normals;
  100851. vertexData.uvs = handledMesh.uvs;
  100852. vertexData.indices = handledMesh.indices;
  100853. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  100854. vertexData.applyToMesh(babylonMesh);
  100855. if (OBJFileLoader.INVERT_Y) {
  100856. babylonMesh.scaling.y *= -1;
  100857. }
  100858. //Push the mesh into an array
  100859. babylonMeshesArray.push(babylonMesh);
  100860. }
  100861. //load the materials
  100862. //Check if we have a file to load
  100863. if (fileToLoad !== "") {
  100864. //Load the file synchronously
  100865. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  100866. //Create materials thanks MTLLoader function
  100867. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  100868. //Look at each material loaded in the mtl file
  100869. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  100870. //Three variables to get all meshes with the same material
  100871. var startIndex = 0;
  100872. var _indices = [];
  100873. var _index;
  100874. //The material from MTL file is used in the meshes loaded
  100875. //Push the indice in an array
  100876. //Check if the material is not used for another mesh
  100877. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  100878. _indices.push(_index);
  100879. startIndex = _index + 1;
  100880. }
  100881. //If the material is not used dispose it
  100882. if (_index == -1 && _indices.length == 0) {
  100883. //If the material is not needed, remove it
  100884. materialsFromMTLFile.materials[n].dispose();
  100885. }
  100886. else {
  100887. for (var o = 0; o < _indices.length; o++) {
  100888. //Apply the material to the BABYLON.Mesh for each mesh with the material
  100889. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  100890. }
  100891. }
  100892. }
  100893. });
  100894. }
  100895. //Return an array with all BABYLON.Mesh
  100896. return babylonMeshesArray;
  100897. };
  100898. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  100899. OBJFileLoader.INVERT_Y = false;
  100900. return OBJFileLoader;
  100901. }());
  100902. BABYLON.OBJFileLoader = OBJFileLoader;
  100903. if (BABYLON.SceneLoader) {
  100904. //Add this loader into the register plugin
  100905. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  100906. }
  100907. })(BABYLON || (BABYLON = {}));
  100908. //# sourceMappingURL=babylon.objFileLoader.js.map
  100909. var BABYLON;
  100910. (function (BABYLON) {
  100911. /**
  100912. * Coordinate system mode that will be used when loading from the gltf file
  100913. */
  100914. var GLTFLoaderCoordinateSystemMode;
  100915. (function (GLTFLoaderCoordinateSystemMode) {
  100916. /**
  100917. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  100918. */
  100919. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  100920. /**
  100921. * Sets the useRightHandedSystem flag on the scene.
  100922. */
  100923. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  100924. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  100925. /**
  100926. * Animation mode that determines which animations should be started when a file is loaded
  100927. */
  100928. var GLTFLoaderAnimationStartMode;
  100929. (function (GLTFLoaderAnimationStartMode) {
  100930. /**
  100931. * No animation will start.
  100932. */
  100933. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  100934. /**
  100935. * The first animation will start.
  100936. */
  100937. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  100938. /**
  100939. * All animations will start.
  100940. */
  100941. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  100942. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  100943. /**
  100944. * Loading state
  100945. */
  100946. var GLTFLoaderState;
  100947. (function (GLTFLoaderState) {
  100948. /**
  100949. * The asset is loading.
  100950. */
  100951. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  100952. /**
  100953. * The asset is ready for rendering.
  100954. */
  100955. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  100956. /**
  100957. * The asset is completely loaded.
  100958. */
  100959. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  100960. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  100961. /** File loader to load gltf files into a babylon scene */
  100962. var GLTFFileLoader = /** @class */ (function () {
  100963. function GLTFFileLoader() {
  100964. // #region Common options
  100965. /**
  100966. * Raised when the asset has been parsed.
  100967. * The data.json property stores the glTF JSON.
  100968. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  100969. */
  100970. this.onParsedObservable = new BABYLON.Observable();
  100971. // #endregion
  100972. // #region V2 options
  100973. /**
  100974. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED). Defaults to AUTO.
  100975. * - AUTO - Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  100976. * - FORCE_RIGHT_HANDED - Sets the useRightHandedSystem flag on the scene.
  100977. */
  100978. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  100979. /**
  100980. * The animation start mode (NONE, FIRST, ALL). Defaults to FIRST.
  100981. * - NONE - No animation will start.
  100982. * - FIRST - The first animation will start.
  100983. * - ALL - All animations will start.
  100984. */
  100985. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  100986. /**
  100987. * Set to true to compile materials before raising the success callback. Defaults to false.
  100988. */
  100989. this.compileMaterials = false;
  100990. /**
  100991. * Set to true to also compile materials with clip planes. Defaults to false.
  100992. */
  100993. this.useClipPlane = false;
  100994. /**
  100995. * Set to true to compile shadow generators before raising the success callback. Defaults to false.
  100996. */
  100997. this.compileShadowGenerators = false;
  100998. /**
  100999. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101000. */
  101001. this.onMeshLoadedObservable = new BABYLON.Observable();
  101002. /**
  101003. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  101004. */
  101005. this.onTextureLoadedObservable = new BABYLON.Observable();
  101006. /**
  101007. * Raised when the loader creates a material after parsing the glTF properties of the material.
  101008. */
  101009. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101010. /**
  101011. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  101012. * For assets with LODs, raised when all of the LODs are complete.
  101013. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101014. */
  101015. this.onCompleteObservable = new BABYLON.Observable();
  101016. /**
  101017. * Raised after the loader is disposed.
  101018. */
  101019. this.onDisposeObservable = new BABYLON.Observable();
  101020. /**
  101021. * Raised after a loader extension is created.
  101022. * Set additional options for a loader extension in this event.
  101023. */
  101024. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101025. // #endregion
  101026. this._loader = null;
  101027. /**
  101028. * Name of the loader ("gltf")
  101029. */
  101030. this.name = "gltf";
  101031. /**
  101032. * Supported file extensions of the loader (.gltf, .glb)
  101033. */
  101034. this.extensions = {
  101035. ".gltf": { isBinary: false },
  101036. ".glb": { isBinary: true }
  101037. };
  101038. }
  101039. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101040. /** Raised when the asset has been parsed. */
  101041. set: function (callback) {
  101042. if (this._onParsedObserver) {
  101043. this.onParsedObservable.remove(this._onParsedObserver);
  101044. }
  101045. this._onParsedObserver = this.onParsedObservable.add(callback);
  101046. },
  101047. enumerable: true,
  101048. configurable: true
  101049. });
  101050. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101051. /**
  101052. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh. (onMeshLoadedObservable is likely desired instead.)
  101053. */
  101054. set: function (callback) {
  101055. if (this._onMeshLoadedObserver) {
  101056. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101057. }
  101058. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101059. },
  101060. enumerable: true,
  101061. configurable: true
  101062. });
  101063. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  101064. /**
  101065. * Method called when a texture has been loaded (onTextureLoadedObservable is likely desired instead.)
  101066. */
  101067. set: function (callback) {
  101068. if (this._onTextureLoadedObserver) {
  101069. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  101070. }
  101071. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  101072. },
  101073. enumerable: true,
  101074. configurable: true
  101075. });
  101076. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  101077. /**
  101078. * Method when the loader creates a material after parsing the glTF properties of the material. (onMaterialLoadedObservable is likely desired instead.)
  101079. */
  101080. set: function (callback) {
  101081. if (this._onMaterialLoadedObserver) {
  101082. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  101083. }
  101084. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  101085. },
  101086. enumerable: true,
  101087. configurable: true
  101088. });
  101089. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  101090. /**
  101091. * Raised when the asset is completely loaded, immediately before the loader is disposed. (onCompleteObservable is likely desired instead.)
  101092. */
  101093. set: function (callback) {
  101094. if (this._onCompleteObserver) {
  101095. this.onCompleteObservable.remove(this._onCompleteObserver);
  101096. }
  101097. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  101098. },
  101099. enumerable: true,
  101100. configurable: true
  101101. });
  101102. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  101103. /**
  101104. * Raised after the loader is disposed. (onDisposeObservable is likely desired instead.)
  101105. */
  101106. set: function (callback) {
  101107. if (this._onDisposeObserver) {
  101108. this.onDisposeObservable.remove(this._onDisposeObserver);
  101109. }
  101110. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101111. },
  101112. enumerable: true,
  101113. configurable: true
  101114. });
  101115. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  101116. /**
  101117. * Raised after a loader extension is created. (onExtensionLoadedObservable is likely desired instead.)
  101118. */
  101119. set: function (callback) {
  101120. if (this._onExtensionLoadedObserver) {
  101121. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  101122. }
  101123. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  101124. },
  101125. enumerable: true,
  101126. configurable: true
  101127. });
  101128. /**
  101129. * Returns a promise that resolves when the asset is completely loaded.
  101130. * @returns A promise that resolves when the asset is completely loaded.
  101131. */
  101132. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  101133. var _this = this;
  101134. return new Promise(function (resolve) {
  101135. _this.onCompleteObservable.add(function () {
  101136. resolve();
  101137. }, undefined, undefined, undefined, true);
  101138. });
  101139. };
  101140. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  101141. /**
  101142. * The loader state (LOADING, READY, COMPLETE) or null if the loader is not active.
  101143. */
  101144. get: function () {
  101145. return this._loader ? this._loader.state : null;
  101146. },
  101147. enumerable: true,
  101148. configurable: true
  101149. });
  101150. /**
  101151. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  101152. */
  101153. GLTFFileLoader.prototype.dispose = function () {
  101154. if (this._loader) {
  101155. this._loader.dispose();
  101156. this._loader = null;
  101157. }
  101158. this.onMeshLoadedObservable.clear();
  101159. this.onTextureLoadedObservable.clear();
  101160. this.onMaterialLoadedObservable.clear();
  101161. this.onDisposeObservable.notifyObservers(this);
  101162. this.onDisposeObservable.clear();
  101163. };
  101164. /**
  101165. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  101166. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  101167. * @param scene the scene the meshes should be added to
  101168. * @param data gltf data containing information of the meshes in a loaded file
  101169. * @param rootUrl root url to load from
  101170. * @param onProgress event that fires when loading progress has occured
  101171. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  101172. */
  101173. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101174. var _this = this;
  101175. return Promise.resolve().then(function () {
  101176. var loaderData = _this._parse(data);
  101177. _this._loader = _this._getLoader(loaderData);
  101178. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  101179. });
  101180. };
  101181. /**
  101182. * Imports all objects from a loaded gltf file and adds them to the scene
  101183. * @param scene the scene the objects should be added to
  101184. * @param data gltf data containing information of the meshes in a loaded file
  101185. * @param rootUrl root url to load from
  101186. * @param onProgress event that fires when loading progress has occured
  101187. * @returns a promise which completes when objects have been loaded to the scene
  101188. */
  101189. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101190. var _this = this;
  101191. return Promise.resolve().then(function () {
  101192. var loaderData = _this._parse(data);
  101193. _this._loader = _this._getLoader(loaderData);
  101194. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  101195. });
  101196. };
  101197. /**
  101198. * Load into an asset container.
  101199. * @param scene The scene to load into
  101200. * @param data The data to import
  101201. * @param rootUrl The root url for scene and resources
  101202. * @param onProgress The callback when the load progresses
  101203. * @returns The loaded asset container
  101204. */
  101205. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  101206. var _this = this;
  101207. return Promise.resolve().then(function () {
  101208. var loaderData = _this._parse(data);
  101209. _this._loader = _this._getLoader(loaderData);
  101210. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  101211. var container = new BABYLON.AssetContainer(scene);
  101212. Array.prototype.push.apply(container.meshes, result.meshes);
  101213. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  101214. Array.prototype.push.apply(container.skeletons, result.skeletons);
  101215. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  101216. container.removeAllFromScene();
  101217. return container;
  101218. });
  101219. });
  101220. };
  101221. /**
  101222. * If the data string can be loaded directly
  101223. * @param data string contianing the file data
  101224. * @returns if the data can be loaded directly
  101225. */
  101226. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  101227. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  101228. };
  101229. /**
  101230. * Instantiates a gltf file loader plugin
  101231. * @returns the created plugin
  101232. */
  101233. GLTFFileLoader.prototype.createPlugin = function () {
  101234. return new GLTFFileLoader();
  101235. };
  101236. GLTFFileLoader.prototype._parse = function (data) {
  101237. var parsedData;
  101238. if (data instanceof ArrayBuffer) {
  101239. parsedData = GLTFFileLoader._parseBinary(data);
  101240. }
  101241. else {
  101242. parsedData = {
  101243. json: JSON.parse(data),
  101244. bin: null
  101245. };
  101246. }
  101247. this.onParsedObservable.notifyObservers(parsedData);
  101248. this.onParsedObservable.clear();
  101249. return parsedData;
  101250. };
  101251. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  101252. var _this = this;
  101253. var loaderVersion = { major: 2, minor: 0 };
  101254. var asset = loaderData.json.asset || {};
  101255. var version = GLTFFileLoader._parseVersion(asset.version);
  101256. if (!version) {
  101257. throw new Error("Invalid version: " + asset.version);
  101258. }
  101259. if (asset.minVersion !== undefined) {
  101260. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  101261. if (!minVersion) {
  101262. throw new Error("Invalid minimum version: " + asset.minVersion);
  101263. }
  101264. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  101265. throw new Error("Incompatible minimum version: " + asset.minVersion);
  101266. }
  101267. }
  101268. var createLoaders = {
  101269. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  101270. 2: GLTFFileLoader.CreateGLTFLoaderV2
  101271. };
  101272. var createLoader = createLoaders[version.major];
  101273. if (!createLoader) {
  101274. throw new Error("Unsupported version: " + asset.version);
  101275. }
  101276. var loader = createLoader();
  101277. loader.coordinateSystemMode = this.coordinateSystemMode;
  101278. loader.animationStartMode = this.animationStartMode;
  101279. loader.compileMaterials = this.compileMaterials;
  101280. loader.useClipPlane = this.useClipPlane;
  101281. loader.compileShadowGenerators = this.compileShadowGenerators;
  101282. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  101283. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  101284. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  101285. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  101286. loader.onCompleteObservable.add(function () {
  101287. _this.onMeshLoadedObservable.clear();
  101288. _this.onTextureLoadedObservable.clear();
  101289. _this.onMaterialLoadedObservable.clear();
  101290. _this.onCompleteObservable.notifyObservers(_this);
  101291. _this.onCompleteObservable.clear();
  101292. });
  101293. return loader;
  101294. };
  101295. GLTFFileLoader._parseBinary = function (data) {
  101296. var Binary = {
  101297. Magic: 0x46546C67
  101298. };
  101299. var binaryReader = new BinaryReader(data);
  101300. var magic = binaryReader.readUint32();
  101301. if (magic !== Binary.Magic) {
  101302. throw new Error("Unexpected magic: " + magic);
  101303. }
  101304. var version = binaryReader.readUint32();
  101305. switch (version) {
  101306. case 1: return GLTFFileLoader._parseV1(binaryReader);
  101307. case 2: return GLTFFileLoader._parseV2(binaryReader);
  101308. }
  101309. throw new Error("Unsupported version: " + version);
  101310. };
  101311. GLTFFileLoader._parseV1 = function (binaryReader) {
  101312. var ContentFormat = {
  101313. JSON: 0
  101314. };
  101315. var length = binaryReader.readUint32();
  101316. if (length != binaryReader.getLength()) {
  101317. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101318. }
  101319. var contentLength = binaryReader.readUint32();
  101320. var contentFormat = binaryReader.readUint32();
  101321. var content;
  101322. switch (contentFormat) {
  101323. case ContentFormat.JSON: {
  101324. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101325. break;
  101326. }
  101327. default: {
  101328. throw new Error("Unexpected content format: " + contentFormat);
  101329. }
  101330. }
  101331. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  101332. var body = binaryReader.readUint8Array(bytesRemaining);
  101333. return {
  101334. json: content,
  101335. bin: body
  101336. };
  101337. };
  101338. GLTFFileLoader._parseV2 = function (binaryReader) {
  101339. var ChunkFormat = {
  101340. JSON: 0x4E4F534A,
  101341. BIN: 0x004E4942
  101342. };
  101343. var length = binaryReader.readUint32();
  101344. if (length !== binaryReader.getLength()) {
  101345. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101346. }
  101347. // JSON chunk
  101348. var chunkLength = binaryReader.readUint32();
  101349. var chunkFormat = binaryReader.readUint32();
  101350. if (chunkFormat !== ChunkFormat.JSON) {
  101351. throw new Error("First chunk format is not JSON");
  101352. }
  101353. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  101354. // Look for BIN chunk
  101355. var bin = null;
  101356. while (binaryReader.getPosition() < binaryReader.getLength()) {
  101357. var chunkLength_1 = binaryReader.readUint32();
  101358. var chunkFormat_1 = binaryReader.readUint32();
  101359. switch (chunkFormat_1) {
  101360. case ChunkFormat.JSON: {
  101361. throw new Error("Unexpected JSON chunk");
  101362. }
  101363. case ChunkFormat.BIN: {
  101364. bin = binaryReader.readUint8Array(chunkLength_1);
  101365. break;
  101366. }
  101367. default: {
  101368. // ignore unrecognized chunkFormat
  101369. binaryReader.skipBytes(chunkLength_1);
  101370. break;
  101371. }
  101372. }
  101373. }
  101374. return {
  101375. json: json,
  101376. bin: bin
  101377. };
  101378. };
  101379. GLTFFileLoader._parseVersion = function (version) {
  101380. if (version === "1.0" || version === "1.0.1") {
  101381. return {
  101382. major: 1,
  101383. minor: 0
  101384. };
  101385. }
  101386. var match = (version + "").match(/^(\d+)\.(\d+)/);
  101387. if (!match) {
  101388. return null;
  101389. }
  101390. return {
  101391. major: parseInt(match[1]),
  101392. minor: parseInt(match[2])
  101393. };
  101394. };
  101395. GLTFFileLoader._compareVersion = function (a, b) {
  101396. if (a.major > b.major)
  101397. return 1;
  101398. if (a.major < b.major)
  101399. return -1;
  101400. if (a.minor > b.minor)
  101401. return 1;
  101402. if (a.minor < b.minor)
  101403. return -1;
  101404. return 0;
  101405. };
  101406. GLTFFileLoader._decodeBufferToText = function (buffer) {
  101407. var result = "";
  101408. var length = buffer.byteLength;
  101409. for (var i = 0; i < length; i++) {
  101410. result += String.fromCharCode(buffer[i]);
  101411. }
  101412. return result;
  101413. };
  101414. // #endregion
  101415. // #region V1 options
  101416. /**
  101417. * Set this property to false to disable incremental loading which delays the loader from calling the success callback until after loading the meshes and shaders. Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled. Defaults to true.
  101418. */
  101419. GLTFFileLoader.IncrementalLoading = true;
  101420. /**
  101421. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters. Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates
  101422. */
  101423. GLTFFileLoader.HomogeneousCoordinates = false;
  101424. return GLTFFileLoader;
  101425. }());
  101426. BABYLON.GLTFFileLoader = GLTFFileLoader;
  101427. var BinaryReader = /** @class */ (function () {
  101428. function BinaryReader(arrayBuffer) {
  101429. this._arrayBuffer = arrayBuffer;
  101430. this._dataView = new DataView(arrayBuffer);
  101431. this._byteOffset = 0;
  101432. }
  101433. BinaryReader.prototype.getPosition = function () {
  101434. return this._byteOffset;
  101435. };
  101436. BinaryReader.prototype.getLength = function () {
  101437. return this._arrayBuffer.byteLength;
  101438. };
  101439. BinaryReader.prototype.readUint32 = function () {
  101440. var value = this._dataView.getUint32(this._byteOffset, true);
  101441. this._byteOffset += 4;
  101442. return value;
  101443. };
  101444. BinaryReader.prototype.readUint8Array = function (length) {
  101445. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  101446. this._byteOffset += length;
  101447. return value;
  101448. };
  101449. BinaryReader.prototype.skipBytes = function (length) {
  101450. this._byteOffset += length;
  101451. };
  101452. return BinaryReader;
  101453. }());
  101454. if (BABYLON.SceneLoader) {
  101455. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  101456. }
  101457. })(BABYLON || (BABYLON = {}));
  101458. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  101459. var BABYLON;
  101460. (function (BABYLON) {
  101461. var GLTF1;
  101462. (function (GLTF1) {
  101463. /**
  101464. * Enums
  101465. */
  101466. var EComponentType;
  101467. (function (EComponentType) {
  101468. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  101469. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101470. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  101471. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101472. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  101473. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  101474. var EShaderType;
  101475. (function (EShaderType) {
  101476. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  101477. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  101478. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  101479. var EParameterType;
  101480. (function (EParameterType) {
  101481. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  101482. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  101483. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  101484. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  101485. EParameterType[EParameterType["INT"] = 5124] = "INT";
  101486. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  101487. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  101488. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  101489. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  101490. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  101491. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  101492. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  101493. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  101494. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  101495. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  101496. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  101497. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  101498. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  101499. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  101500. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  101501. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  101502. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  101503. var ETextureWrapMode;
  101504. (function (ETextureWrapMode) {
  101505. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  101506. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  101507. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  101508. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  101509. var ETextureFilterType;
  101510. (function (ETextureFilterType) {
  101511. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  101512. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  101513. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  101514. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  101515. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  101516. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  101517. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  101518. var ETextureFormat;
  101519. (function (ETextureFormat) {
  101520. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  101521. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  101522. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  101523. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  101524. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  101525. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  101526. var ECullingType;
  101527. (function (ECullingType) {
  101528. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  101529. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  101530. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  101531. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  101532. var EBlendingFunction;
  101533. (function (EBlendingFunction) {
  101534. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  101535. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  101536. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  101537. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  101538. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  101539. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  101540. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  101541. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  101542. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  101543. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  101544. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  101545. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  101546. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  101547. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  101548. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  101549. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  101550. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  101551. })(BABYLON || (BABYLON = {}));
  101552. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  101553. var BABYLON;
  101554. (function (BABYLON) {
  101555. var GLTF1;
  101556. (function (GLTF1) {
  101557. /**
  101558. * Tokenizer. Used for shaders compatibility
  101559. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  101560. */
  101561. var ETokenType;
  101562. (function (ETokenType) {
  101563. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  101564. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  101565. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  101566. })(ETokenType || (ETokenType = {}));
  101567. var Tokenizer = /** @class */ (function () {
  101568. function Tokenizer(toParse) {
  101569. this._pos = 0;
  101570. this.currentToken = ETokenType.UNKNOWN;
  101571. this.currentIdentifier = "";
  101572. this.currentString = "";
  101573. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  101574. this._toParse = toParse;
  101575. this._maxPos = toParse.length;
  101576. }
  101577. Tokenizer.prototype.getNextToken = function () {
  101578. if (this.isEnd())
  101579. return ETokenType.END_OF_INPUT;
  101580. this.currentString = this.read();
  101581. this.currentToken = ETokenType.UNKNOWN;
  101582. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  101583. this.currentToken = ETokenType.IDENTIFIER;
  101584. this.currentIdentifier = this.currentString;
  101585. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  101586. this.currentIdentifier += this.currentString;
  101587. this.forward();
  101588. }
  101589. }
  101590. return this.currentToken;
  101591. };
  101592. Tokenizer.prototype.peek = function () {
  101593. return this._toParse[this._pos];
  101594. };
  101595. Tokenizer.prototype.read = function () {
  101596. return this._toParse[this._pos++];
  101597. };
  101598. Tokenizer.prototype.forward = function () {
  101599. this._pos++;
  101600. };
  101601. Tokenizer.prototype.isEnd = function () {
  101602. return this._pos >= this._maxPos;
  101603. };
  101604. return Tokenizer;
  101605. }());
  101606. /**
  101607. * Values
  101608. */
  101609. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  101610. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  101611. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  101612. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  101613. /**
  101614. * Parse
  101615. */
  101616. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  101617. for (var buf in parsedBuffers) {
  101618. var parsedBuffer = parsedBuffers[buf];
  101619. gltfRuntime.buffers[buf] = parsedBuffer;
  101620. gltfRuntime.buffersCount++;
  101621. }
  101622. };
  101623. var parseShaders = function (parsedShaders, gltfRuntime) {
  101624. for (var sha in parsedShaders) {
  101625. var parsedShader = parsedShaders[sha];
  101626. gltfRuntime.shaders[sha] = parsedShader;
  101627. gltfRuntime.shaderscount++;
  101628. }
  101629. };
  101630. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  101631. for (var object in parsedObjects) {
  101632. var parsedObject = parsedObjects[object];
  101633. gltfRuntime[runtimeProperty][object] = parsedObject;
  101634. }
  101635. };
  101636. /**
  101637. * Utils
  101638. */
  101639. var normalizeUVs = function (buffer) {
  101640. if (!buffer) {
  101641. return;
  101642. }
  101643. for (var i = 0; i < buffer.length / 2; i++) {
  101644. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  101645. }
  101646. };
  101647. var getAttribute = function (attributeParameter) {
  101648. if (attributeParameter.semantic === "NORMAL") {
  101649. return "normal";
  101650. }
  101651. else if (attributeParameter.semantic === "POSITION") {
  101652. return "position";
  101653. }
  101654. else if (attributeParameter.semantic === "JOINT") {
  101655. return "matricesIndices";
  101656. }
  101657. else if (attributeParameter.semantic === "WEIGHT") {
  101658. return "matricesWeights";
  101659. }
  101660. else if (attributeParameter.semantic === "COLOR") {
  101661. return "color";
  101662. }
  101663. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  101664. var channel = Number(attributeParameter.semantic.split("_")[1]);
  101665. return "uv" + (channel === 0 ? "" : channel + 1);
  101666. }
  101667. return null;
  101668. };
  101669. /**
  101670. * Loads and creates animations
  101671. */
  101672. var loadAnimations = function (gltfRuntime) {
  101673. for (var anim in gltfRuntime.animations) {
  101674. var animation = gltfRuntime.animations[anim];
  101675. if (!animation.channels || !animation.samplers) {
  101676. continue;
  101677. }
  101678. var lastAnimation = null;
  101679. for (var i = 0; i < animation.channels.length; i++) {
  101680. // Get parameters and load buffers
  101681. var channel = animation.channels[i];
  101682. var sampler = animation.samplers[channel.sampler];
  101683. if (!sampler) {
  101684. continue;
  101685. }
  101686. var inputData = null;
  101687. var outputData = null;
  101688. if (animation.parameters) {
  101689. inputData = animation.parameters[sampler.input];
  101690. outputData = animation.parameters[sampler.output];
  101691. }
  101692. else {
  101693. inputData = sampler.input;
  101694. outputData = sampler.output;
  101695. }
  101696. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  101697. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  101698. var targetID = channel.target.id;
  101699. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  101700. if (targetNode === null) {
  101701. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  101702. }
  101703. if (targetNode === null) {
  101704. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  101705. continue;
  101706. }
  101707. var isBone = targetNode instanceof BABYLON.Bone;
  101708. // Get target path (position, rotation or scaling)
  101709. var targetPath = channel.target.path;
  101710. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  101711. if (targetPathIndex !== -1) {
  101712. targetPath = babylonAnimationPaths[targetPathIndex];
  101713. }
  101714. // Determine animation type
  101715. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  101716. if (!isBone) {
  101717. if (targetPath === "rotationQuaternion") {
  101718. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  101719. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  101720. }
  101721. else {
  101722. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  101723. }
  101724. }
  101725. // Create animation and key frames
  101726. var babylonAnimation = null;
  101727. var keys = [];
  101728. var arrayOffset = 0;
  101729. var modifyKey = false;
  101730. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  101731. babylonAnimation = lastAnimation;
  101732. modifyKey = true;
  101733. }
  101734. if (!modifyKey) {
  101735. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  101736. }
  101737. // For each frame
  101738. for (var j = 0; j < bufferInput.length; j++) {
  101739. var value = null;
  101740. if (targetPath === "rotationQuaternion") { // VEC4
  101741. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  101742. arrayOffset += 4;
  101743. }
  101744. else { // Position and scaling are VEC3
  101745. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  101746. arrayOffset += 3;
  101747. }
  101748. if (isBone) {
  101749. var bone = targetNode;
  101750. var translation = BABYLON.Vector3.Zero();
  101751. var rotationQuaternion = new BABYLON.Quaternion();
  101752. var scaling = BABYLON.Vector3.Zero();
  101753. // Warning on decompose
  101754. var mat = bone.getBaseMatrix();
  101755. if (modifyKey && lastAnimation) {
  101756. mat = lastAnimation.getKeys()[j].value;
  101757. }
  101758. mat.decompose(scaling, rotationQuaternion, translation);
  101759. if (targetPath === "position") {
  101760. translation = value;
  101761. }
  101762. else if (targetPath === "rotationQuaternion") {
  101763. rotationQuaternion = value;
  101764. }
  101765. else {
  101766. scaling = value;
  101767. }
  101768. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  101769. }
  101770. if (!modifyKey) {
  101771. keys.push({
  101772. frame: bufferInput[j],
  101773. value: value
  101774. });
  101775. }
  101776. else if (lastAnimation) {
  101777. lastAnimation.getKeys()[j].value = value;
  101778. }
  101779. }
  101780. // Finish
  101781. if (!modifyKey && babylonAnimation) {
  101782. babylonAnimation.setKeys(keys);
  101783. targetNode.animations.push(babylonAnimation);
  101784. }
  101785. lastAnimation = babylonAnimation;
  101786. gltfRuntime.scene.stopAnimation(targetNode);
  101787. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  101788. }
  101789. }
  101790. };
  101791. /**
  101792. * Returns the bones transformation matrix
  101793. */
  101794. var configureBoneTransformation = function (node) {
  101795. var mat = null;
  101796. if (node.translation || node.rotation || node.scale) {
  101797. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  101798. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  101799. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  101800. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  101801. }
  101802. else {
  101803. mat = BABYLON.Matrix.FromArray(node.matrix);
  101804. }
  101805. return mat;
  101806. };
  101807. /**
  101808. * Returns the parent bone
  101809. */
  101810. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  101811. // Try to find
  101812. for (var i = 0; i < newSkeleton.bones.length; i++) {
  101813. if (newSkeleton.bones[i].name === jointName) {
  101814. return newSkeleton.bones[i];
  101815. }
  101816. }
  101817. // Not found, search in gltf nodes
  101818. var nodes = gltfRuntime.nodes;
  101819. for (var nde in nodes) {
  101820. var node = nodes[nde];
  101821. if (!node.jointName) {
  101822. continue;
  101823. }
  101824. var children = node.children;
  101825. for (var i = 0; i < children.length; i++) {
  101826. var child = gltfRuntime.nodes[children[i]];
  101827. if (!child.jointName) {
  101828. continue;
  101829. }
  101830. if (child.jointName === jointName) {
  101831. var mat = configureBoneTransformation(node);
  101832. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  101833. bone.id = nde;
  101834. return bone;
  101835. }
  101836. }
  101837. }
  101838. return null;
  101839. };
  101840. /**
  101841. * Returns the appropriate root node
  101842. */
  101843. var getNodeToRoot = function (nodesToRoot, id) {
  101844. for (var i = 0; i < nodesToRoot.length; i++) {
  101845. var nodeToRoot = nodesToRoot[i];
  101846. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  101847. var child = nodeToRoot.node.children[j];
  101848. if (child === id) {
  101849. return nodeToRoot.bone;
  101850. }
  101851. }
  101852. }
  101853. return null;
  101854. };
  101855. /**
  101856. * Returns the node with the joint name
  101857. */
  101858. var getJointNode = function (gltfRuntime, jointName) {
  101859. var nodes = gltfRuntime.nodes;
  101860. var node = nodes[jointName];
  101861. if (node) {
  101862. return {
  101863. node: node,
  101864. id: jointName
  101865. };
  101866. }
  101867. for (var nde in nodes) {
  101868. node = nodes[nde];
  101869. if (node.jointName === jointName) {
  101870. return {
  101871. node: node,
  101872. id: nde
  101873. };
  101874. }
  101875. }
  101876. return null;
  101877. };
  101878. /**
  101879. * Checks if a nodes is in joints
  101880. */
  101881. var nodeIsInJoints = function (skins, id) {
  101882. for (var i = 0; i < skins.jointNames.length; i++) {
  101883. if (skins.jointNames[i] === id) {
  101884. return true;
  101885. }
  101886. }
  101887. return false;
  101888. };
  101889. /**
  101890. * Fills the nodes to root for bones and builds hierarchy
  101891. */
  101892. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  101893. // Creates nodes for root
  101894. for (var nde in gltfRuntime.nodes) {
  101895. var node = gltfRuntime.nodes[nde];
  101896. var id = nde;
  101897. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  101898. continue;
  101899. }
  101900. // Create node to root bone
  101901. var mat = configureBoneTransformation(node);
  101902. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  101903. bone.id = id;
  101904. nodesToRoot.push({ bone: bone, node: node, id: id });
  101905. }
  101906. // Parenting
  101907. for (var i = 0; i < nodesToRoot.length; i++) {
  101908. var nodeToRoot = nodesToRoot[i];
  101909. var children = nodeToRoot.node.children;
  101910. for (var j = 0; j < children.length; j++) {
  101911. var child = null;
  101912. for (var k = 0; k < nodesToRoot.length; k++) {
  101913. if (nodesToRoot[k].id === children[j]) {
  101914. child = nodesToRoot[k];
  101915. break;
  101916. }
  101917. }
  101918. if (child) {
  101919. child.bone._parent = nodeToRoot.bone;
  101920. nodeToRoot.bone.children.push(child.bone);
  101921. }
  101922. }
  101923. }
  101924. };
  101925. /**
  101926. * Imports a skeleton
  101927. */
  101928. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  101929. if (!newSkeleton) {
  101930. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  101931. }
  101932. if (!skins.babylonSkeleton) {
  101933. return newSkeleton;
  101934. }
  101935. // Find the root bones
  101936. var nodesToRoot = [];
  101937. var nodesToRootToAdd = [];
  101938. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  101939. newSkeleton.bones = [];
  101940. // Joints
  101941. for (var i = 0; i < skins.jointNames.length; i++) {
  101942. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  101943. if (!jointNode) {
  101944. continue;
  101945. }
  101946. var node = jointNode.node;
  101947. if (!node) {
  101948. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  101949. continue;
  101950. }
  101951. var id = jointNode.id;
  101952. // Optimize, if the bone already exists...
  101953. var existingBone = gltfRuntime.scene.getBoneByID(id);
  101954. if (existingBone) {
  101955. newSkeleton.bones.push(existingBone);
  101956. continue;
  101957. }
  101958. // Search for parent bone
  101959. var foundBone = false;
  101960. var parentBone = null;
  101961. for (var j = 0; j < i; j++) {
  101962. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  101963. if (!jointNode_1) {
  101964. continue;
  101965. }
  101966. var joint = jointNode_1.node;
  101967. if (!joint) {
  101968. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  101969. continue;
  101970. }
  101971. var children = joint.children;
  101972. if (!children) {
  101973. continue;
  101974. }
  101975. foundBone = false;
  101976. for (var k = 0; k < children.length; k++) {
  101977. if (children[k] === id) {
  101978. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  101979. foundBone = true;
  101980. break;
  101981. }
  101982. }
  101983. if (foundBone) {
  101984. break;
  101985. }
  101986. }
  101987. // Create bone
  101988. var mat = configureBoneTransformation(node);
  101989. if (!parentBone && nodesToRoot.length > 0) {
  101990. parentBone = getNodeToRoot(nodesToRoot, id);
  101991. if (parentBone) {
  101992. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  101993. nodesToRootToAdd.push(parentBone);
  101994. }
  101995. }
  101996. }
  101997. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  101998. bone.id = id;
  101999. }
  102000. // Polish
  102001. var bones = newSkeleton.bones;
  102002. newSkeleton.bones = [];
  102003. for (var i = 0; i < skins.jointNames.length; i++) {
  102004. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102005. if (!jointNode) {
  102006. continue;
  102007. }
  102008. for (var j = 0; j < bones.length; j++) {
  102009. if (bones[j].id === jointNode.id) {
  102010. newSkeleton.bones.push(bones[j]);
  102011. break;
  102012. }
  102013. }
  102014. }
  102015. newSkeleton.prepare();
  102016. // Finish
  102017. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102018. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102019. }
  102020. return newSkeleton;
  102021. };
  102022. /**
  102023. * Imports a mesh and its geometries
  102024. */
  102025. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102026. if (!newMesh) {
  102027. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102028. newMesh.id = id;
  102029. }
  102030. if (!node.babylonNode) {
  102031. return newMesh;
  102032. }
  102033. var subMaterials = [];
  102034. var vertexData = null;
  102035. var verticesStarts = new Array();
  102036. var verticesCounts = new Array();
  102037. var indexStarts = new Array();
  102038. var indexCounts = new Array();
  102039. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102040. var meshID = meshes[meshIndex];
  102041. var mesh = gltfRuntime.meshes[meshID];
  102042. if (!mesh) {
  102043. continue;
  102044. }
  102045. // Positions, normals and UVs
  102046. for (var i = 0; i < mesh.primitives.length; i++) {
  102047. // Temporary vertex data
  102048. var tempVertexData = new BABYLON.VertexData();
  102049. var primitive = mesh.primitives[i];
  102050. if (primitive.mode !== 4) {
  102051. // continue;
  102052. }
  102053. var attributes = primitive.attributes;
  102054. var accessor = null;
  102055. var buffer = null;
  102056. // Set positions, normal and uvs
  102057. for (var semantic in attributes) {
  102058. // Link accessor and buffer view
  102059. accessor = gltfRuntime.accessors[attributes[semantic]];
  102060. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102061. if (semantic === "NORMAL") {
  102062. tempVertexData.normals = new Float32Array(buffer.length);
  102063. tempVertexData.normals.set(buffer);
  102064. }
  102065. else if (semantic === "POSITION") {
  102066. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  102067. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  102068. for (var j = 0; j < buffer.length; j += 4) {
  102069. tempVertexData.positions[j] = buffer[j];
  102070. tempVertexData.positions[j + 1] = buffer[j + 1];
  102071. tempVertexData.positions[j + 2] = buffer[j + 2];
  102072. }
  102073. }
  102074. else {
  102075. tempVertexData.positions = new Float32Array(buffer.length);
  102076. tempVertexData.positions.set(buffer);
  102077. }
  102078. verticesCounts.push(tempVertexData.positions.length);
  102079. }
  102080. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  102081. var channel = Number(semantic.split("_")[1]);
  102082. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  102083. var uvs = new Float32Array(buffer.length);
  102084. uvs.set(buffer);
  102085. normalizeUVs(uvs);
  102086. tempVertexData.set(uvs, uvKind);
  102087. }
  102088. else if (semantic === "JOINT") {
  102089. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  102090. tempVertexData.matricesIndices.set(buffer);
  102091. }
  102092. else if (semantic === "WEIGHT") {
  102093. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  102094. tempVertexData.matricesWeights.set(buffer);
  102095. }
  102096. else if (semantic === "COLOR") {
  102097. tempVertexData.colors = new Float32Array(buffer.length);
  102098. tempVertexData.colors.set(buffer);
  102099. }
  102100. }
  102101. // Indices
  102102. accessor = gltfRuntime.accessors[primitive.indices];
  102103. if (accessor) {
  102104. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102105. tempVertexData.indices = new Int32Array(buffer.length);
  102106. tempVertexData.indices.set(buffer);
  102107. indexCounts.push(tempVertexData.indices.length);
  102108. }
  102109. else {
  102110. // Set indices on the fly
  102111. var indices = [];
  102112. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  102113. indices.push(j);
  102114. }
  102115. tempVertexData.indices = new Int32Array(indices);
  102116. indexCounts.push(tempVertexData.indices.length);
  102117. }
  102118. if (!vertexData) {
  102119. vertexData = tempVertexData;
  102120. }
  102121. else {
  102122. vertexData.merge(tempVertexData);
  102123. }
  102124. // Sub material
  102125. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  102126. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  102127. // Update vertices start and index start
  102128. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  102129. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  102130. }
  102131. }
  102132. var material;
  102133. if (subMaterials.length > 1) {
  102134. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  102135. material.subMaterials = subMaterials;
  102136. }
  102137. else {
  102138. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  102139. }
  102140. if (subMaterials.length === 1) {
  102141. material = subMaterials[0];
  102142. }
  102143. if (!newMesh.material) {
  102144. newMesh.material = material;
  102145. }
  102146. // Apply geometry
  102147. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  102148. newMesh.computeWorldMatrix(true);
  102149. // Apply submeshes
  102150. newMesh.subMeshes = [];
  102151. var index = 0;
  102152. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102153. var meshID = meshes[meshIndex];
  102154. var mesh = gltfRuntime.meshes[meshID];
  102155. if (!mesh) {
  102156. continue;
  102157. }
  102158. for (var i = 0; i < mesh.primitives.length; i++) {
  102159. if (mesh.primitives[i].mode !== 4) {
  102160. //continue;
  102161. }
  102162. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  102163. index++;
  102164. }
  102165. }
  102166. // Finish
  102167. return newMesh;
  102168. };
  102169. /**
  102170. * Configure node transformation from position, rotation and scaling
  102171. */
  102172. var configureNode = function (newNode, position, rotation, scaling) {
  102173. if (newNode.position) {
  102174. newNode.position = position;
  102175. }
  102176. if (newNode.rotationQuaternion || newNode.rotation) {
  102177. newNode.rotationQuaternion = rotation;
  102178. }
  102179. if (newNode.scaling) {
  102180. newNode.scaling = scaling;
  102181. }
  102182. };
  102183. /**
  102184. * Configures node from transformation matrix
  102185. */
  102186. var configureNodeFromMatrix = function (newNode, node, parent) {
  102187. if (node.matrix) {
  102188. var position = new BABYLON.Vector3(0, 0, 0);
  102189. var rotation = new BABYLON.Quaternion();
  102190. var scaling = new BABYLON.Vector3(0, 0, 0);
  102191. var mat = BABYLON.Matrix.FromArray(node.matrix);
  102192. mat.decompose(scaling, rotation, position);
  102193. configureNode(newNode, position, rotation, scaling);
  102194. }
  102195. else if (node.translation && node.rotation && node.scale) {
  102196. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  102197. }
  102198. newNode.computeWorldMatrix(true);
  102199. };
  102200. /**
  102201. * Imports a node
  102202. */
  102203. var importNode = function (gltfRuntime, node, id, parent) {
  102204. var lastNode = null;
  102205. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  102206. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  102207. return null;
  102208. }
  102209. }
  102210. // Meshes
  102211. if (node.skin) {
  102212. if (node.meshes) {
  102213. var skin = gltfRuntime.skins[node.skin];
  102214. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  102215. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  102216. if (newMesh.skeleton === null) {
  102217. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  102218. if (!skin.babylonSkeleton) {
  102219. skin.babylonSkeleton = newMesh.skeleton;
  102220. }
  102221. }
  102222. lastNode = newMesh;
  102223. }
  102224. }
  102225. else if (node.meshes) {
  102226. /**
  102227. * Improve meshes property
  102228. */
  102229. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  102230. lastNode = newMesh;
  102231. }
  102232. // Lights
  102233. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102234. var light = gltfRuntime.lights[node.light];
  102235. if (light) {
  102236. if (light.type === "ambient") {
  102237. var ambienLight = light[light.type];
  102238. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102239. hemiLight.name = node.name || "";
  102240. if (ambienLight.color) {
  102241. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  102242. }
  102243. lastNode = hemiLight;
  102244. }
  102245. else if (light.type === "directional") {
  102246. var directionalLight = light[light.type];
  102247. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102248. dirLight.name = node.name || "";
  102249. if (directionalLight.color) {
  102250. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  102251. }
  102252. lastNode = dirLight;
  102253. }
  102254. else if (light.type === "point") {
  102255. var pointLight = light[light.type];
  102256. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102257. ptLight.name = node.name || "";
  102258. if (pointLight.color) {
  102259. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  102260. }
  102261. lastNode = ptLight;
  102262. }
  102263. else if (light.type === "spot") {
  102264. var spotLight = light[light.type];
  102265. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  102266. spLight.name = node.name || "";
  102267. if (spotLight.color) {
  102268. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  102269. }
  102270. if (spotLight.fallOfAngle) {
  102271. spLight.angle = spotLight.fallOfAngle;
  102272. }
  102273. if (spotLight.fallOffExponent) {
  102274. spLight.exponent = spotLight.fallOffExponent;
  102275. }
  102276. lastNode = spLight;
  102277. }
  102278. }
  102279. }
  102280. // Cameras
  102281. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102282. var camera = gltfRuntime.cameras[node.camera];
  102283. if (camera) {
  102284. if (camera.type === "orthographic") {
  102285. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102286. orthoCamera.name = node.name || "";
  102287. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  102288. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102289. lastNode = orthoCamera;
  102290. }
  102291. else if (camera.type === "perspective") {
  102292. var perspectiveCamera = camera[camera.type];
  102293. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102294. persCamera.name = node.name || "";
  102295. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102296. if (!perspectiveCamera.aspectRatio) {
  102297. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  102298. }
  102299. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  102300. persCamera.maxZ = perspectiveCamera.zfar;
  102301. persCamera.minZ = perspectiveCamera.znear;
  102302. }
  102303. lastNode = persCamera;
  102304. }
  102305. }
  102306. }
  102307. // Empty node
  102308. if (!node.jointName) {
  102309. if (node.babylonNode) {
  102310. return node.babylonNode;
  102311. }
  102312. else if (lastNode === null) {
  102313. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102314. node.babylonNode = dummy;
  102315. lastNode = dummy;
  102316. }
  102317. }
  102318. if (lastNode !== null) {
  102319. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  102320. configureNodeFromMatrix(lastNode, node, parent);
  102321. }
  102322. else {
  102323. var translation = node.translation || [0, 0, 0];
  102324. var rotation = node.rotation || [0, 0, 0, 1];
  102325. var scale = node.scale || [1, 1, 1];
  102326. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  102327. }
  102328. lastNode.updateCache(true);
  102329. node.babylonNode = lastNode;
  102330. }
  102331. return lastNode;
  102332. };
  102333. /**
  102334. * Traverses nodes and creates them
  102335. */
  102336. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  102337. if (meshIncluded === void 0) { meshIncluded = false; }
  102338. var node = gltfRuntime.nodes[id];
  102339. var newNode = null;
  102340. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  102341. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  102342. meshIncluded = true;
  102343. }
  102344. else {
  102345. meshIncluded = false;
  102346. }
  102347. }
  102348. else {
  102349. meshIncluded = true;
  102350. }
  102351. if (!node.jointName && meshIncluded) {
  102352. newNode = importNode(gltfRuntime, node, id, parent);
  102353. if (newNode !== null) {
  102354. newNode.id = id;
  102355. newNode.parent = parent;
  102356. }
  102357. }
  102358. if (node.children) {
  102359. for (var i = 0; i < node.children.length; i++) {
  102360. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  102361. }
  102362. }
  102363. };
  102364. /**
  102365. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  102366. */
  102367. var postLoad = function (gltfRuntime) {
  102368. // Nodes
  102369. var currentScene = gltfRuntime.currentScene;
  102370. if (currentScene) {
  102371. for (var i = 0; i < currentScene.nodes.length; i++) {
  102372. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102373. }
  102374. }
  102375. else {
  102376. for (var thing in gltfRuntime.scenes) {
  102377. currentScene = gltfRuntime.scenes[thing];
  102378. for (var i = 0; i < currentScene.nodes.length; i++) {
  102379. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102380. }
  102381. }
  102382. }
  102383. // Set animations
  102384. loadAnimations(gltfRuntime);
  102385. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  102386. var skeleton = gltfRuntime.scene.skeletons[i];
  102387. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  102388. }
  102389. };
  102390. /**
  102391. * onBind shaderrs callback to set uniforms and matrices
  102392. */
  102393. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  102394. var materialValues = material.values || technique.parameters;
  102395. for (var unif in unTreatedUniforms) {
  102396. var uniform = unTreatedUniforms[unif];
  102397. var type = uniform.type;
  102398. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  102399. if (uniform.semantic && !uniform.source && !uniform.node) {
  102400. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  102401. }
  102402. else if (uniform.semantic && (uniform.source || uniform.node)) {
  102403. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  102404. if (source === null) {
  102405. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  102406. }
  102407. if (source === null) {
  102408. continue;
  102409. }
  102410. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  102411. }
  102412. }
  102413. else {
  102414. var value = materialValues[technique.uniforms[unif]];
  102415. if (!value) {
  102416. continue;
  102417. }
  102418. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102419. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  102420. if (texture === null || texture === undefined) {
  102421. continue;
  102422. }
  102423. shaderMaterial.getEffect().setTexture(unif, texture);
  102424. }
  102425. else {
  102426. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  102427. }
  102428. }
  102429. }
  102430. onSuccess(shaderMaterial);
  102431. };
  102432. /**
  102433. * Prepare uniforms to send the only one time
  102434. * Loads the appropriate textures
  102435. */
  102436. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  102437. var materialValues = material.values || technique.parameters;
  102438. var techniqueUniforms = technique.uniforms;
  102439. /**
  102440. * Prepare values here (not matrices)
  102441. */
  102442. for (var unif in unTreatedUniforms) {
  102443. var uniform = unTreatedUniforms[unif];
  102444. var type = uniform.type;
  102445. var value = materialValues[techniqueUniforms[unif]];
  102446. if (value === undefined) {
  102447. // In case the value is the same for all materials
  102448. value = uniform.value;
  102449. }
  102450. if (!value) {
  102451. continue;
  102452. }
  102453. var onLoadTexture = function (uniformName) {
  102454. return function (texture) {
  102455. if (uniform.value && uniformName) {
  102456. // Static uniform
  102457. shaderMaterial.setTexture(uniformName, texture);
  102458. delete unTreatedUniforms[uniformName];
  102459. }
  102460. };
  102461. };
  102462. // Texture (sampler2D)
  102463. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  102464. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  102465. }
  102466. // Others
  102467. else {
  102468. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  102469. // Static uniform
  102470. delete unTreatedUniforms[unif];
  102471. }
  102472. }
  102473. }
  102474. };
  102475. /**
  102476. * Shader compilation failed
  102477. */
  102478. var onShaderCompileError = function (program, shaderMaterial, onError) {
  102479. return function (effect, error) {
  102480. shaderMaterial.dispose(true);
  102481. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  102482. };
  102483. };
  102484. /**
  102485. * Shader compilation success
  102486. */
  102487. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  102488. return function (_) {
  102489. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  102490. shaderMaterial.onBind = function (mesh) {
  102491. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  102492. };
  102493. };
  102494. };
  102495. /**
  102496. * Returns the appropriate uniform if already handled by babylon
  102497. */
  102498. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  102499. for (var unif in technique.uniforms) {
  102500. var uniform = technique.uniforms[unif];
  102501. var uniformParameter = technique.parameters[uniform];
  102502. if (tokenizer.currentIdentifier === unif) {
  102503. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  102504. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102505. if (transformIndex !== -1) {
  102506. delete unTreatedUniforms[unif];
  102507. return babylonTransforms[transformIndex];
  102508. }
  102509. }
  102510. }
  102511. }
  102512. return tokenizer.currentIdentifier;
  102513. };
  102514. /**
  102515. * All shaders loaded. Create materials one by one
  102516. */
  102517. var importMaterials = function (gltfRuntime) {
  102518. // Create materials
  102519. for (var mat in gltfRuntime.materials) {
  102520. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  102521. }
  102522. };
  102523. /**
  102524. * Implementation of the base glTF spec
  102525. */
  102526. var GLTFLoaderBase = /** @class */ (function () {
  102527. function GLTFLoaderBase() {
  102528. }
  102529. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  102530. var gltfRuntime = {
  102531. extensions: {},
  102532. accessors: {},
  102533. buffers: {},
  102534. bufferViews: {},
  102535. meshes: {},
  102536. lights: {},
  102537. cameras: {},
  102538. nodes: {},
  102539. images: {},
  102540. textures: {},
  102541. shaders: {},
  102542. programs: {},
  102543. samplers: {},
  102544. techniques: {},
  102545. materials: {},
  102546. animations: {},
  102547. skins: {},
  102548. extensionsUsed: [],
  102549. scenes: {},
  102550. buffersCount: 0,
  102551. shaderscount: 0,
  102552. scene: scene,
  102553. rootUrl: rootUrl,
  102554. loadedBufferCount: 0,
  102555. loadedBufferViews: {},
  102556. loadedShaderCount: 0,
  102557. importOnlyMeshes: false,
  102558. dummyNodes: []
  102559. };
  102560. // Parse
  102561. if (parsedData.extensions) {
  102562. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  102563. }
  102564. if (parsedData.extensionsUsed) {
  102565. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  102566. }
  102567. if (parsedData.buffers) {
  102568. parseBuffers(parsedData.buffers, gltfRuntime);
  102569. }
  102570. if (parsedData.bufferViews) {
  102571. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  102572. }
  102573. if (parsedData.accessors) {
  102574. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  102575. }
  102576. if (parsedData.meshes) {
  102577. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  102578. }
  102579. if (parsedData.lights) {
  102580. parseObject(parsedData.lights, "lights", gltfRuntime);
  102581. }
  102582. if (parsedData.cameras) {
  102583. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  102584. }
  102585. if (parsedData.nodes) {
  102586. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  102587. }
  102588. if (parsedData.images) {
  102589. parseObject(parsedData.images, "images", gltfRuntime);
  102590. }
  102591. if (parsedData.textures) {
  102592. parseObject(parsedData.textures, "textures", gltfRuntime);
  102593. }
  102594. if (parsedData.shaders) {
  102595. parseShaders(parsedData.shaders, gltfRuntime);
  102596. }
  102597. if (parsedData.programs) {
  102598. parseObject(parsedData.programs, "programs", gltfRuntime);
  102599. }
  102600. if (parsedData.samplers) {
  102601. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  102602. }
  102603. if (parsedData.techniques) {
  102604. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  102605. }
  102606. if (parsedData.materials) {
  102607. parseObject(parsedData.materials, "materials", gltfRuntime);
  102608. }
  102609. if (parsedData.animations) {
  102610. parseObject(parsedData.animations, "animations", gltfRuntime);
  102611. }
  102612. if (parsedData.skins) {
  102613. parseObject(parsedData.skins, "skins", gltfRuntime);
  102614. }
  102615. if (parsedData.scenes) {
  102616. gltfRuntime.scenes = parsedData.scenes;
  102617. }
  102618. if (parsedData.scene && parsedData.scenes) {
  102619. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  102620. }
  102621. return gltfRuntime;
  102622. };
  102623. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  102624. var buffer = gltfRuntime.buffers[id];
  102625. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  102626. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  102627. }
  102628. else {
  102629. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  102630. if (request) {
  102631. onError(request.status + " " + request.statusText);
  102632. }
  102633. });
  102634. }
  102635. };
  102636. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  102637. var texture = gltfRuntime.textures[id];
  102638. if (!texture || !texture.source) {
  102639. onError("");
  102640. return;
  102641. }
  102642. if (texture.babylonTexture) {
  102643. onSuccess(null);
  102644. return;
  102645. }
  102646. var source = gltfRuntime.images[texture.source];
  102647. if (BABYLON.Tools.IsBase64(source.uri)) {
  102648. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  102649. }
  102650. else {
  102651. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  102652. if (request) {
  102653. onError(request.status + " " + request.statusText);
  102654. }
  102655. });
  102656. }
  102657. };
  102658. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  102659. var texture = gltfRuntime.textures[id];
  102660. if (texture.babylonTexture) {
  102661. onSuccess(texture.babylonTexture);
  102662. return;
  102663. }
  102664. var sampler = gltfRuntime.samplers[texture.sampler];
  102665. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  102666. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  102667. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  102668. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  102669. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  102670. var blob = new Blob([buffer]);
  102671. var blobURL = URL.createObjectURL(blob);
  102672. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  102673. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  102674. if (sampler.wrapS !== undefined) {
  102675. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  102676. }
  102677. if (sampler.wrapT !== undefined) {
  102678. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  102679. }
  102680. newTexture.name = id;
  102681. texture.babylonTexture = newTexture;
  102682. onSuccess(newTexture);
  102683. };
  102684. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  102685. var shader = gltfRuntime.shaders[id];
  102686. if (BABYLON.Tools.IsBase64(shader.uri)) {
  102687. var shaderString = atob(shader.uri.split(",")[1]);
  102688. if (onSuccess) {
  102689. onSuccess(shaderString);
  102690. }
  102691. }
  102692. else {
  102693. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  102694. if (request && onError) {
  102695. onError(request.status + " " + request.statusText);
  102696. }
  102697. });
  102698. }
  102699. };
  102700. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  102701. var material = gltfRuntime.materials[id];
  102702. if (!material.technique) {
  102703. if (onError) {
  102704. onError("No technique found.");
  102705. }
  102706. return;
  102707. }
  102708. var technique = gltfRuntime.techniques[material.technique];
  102709. if (!technique) {
  102710. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  102711. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  102712. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102713. onSuccess(defaultMaterial);
  102714. return;
  102715. }
  102716. var program = gltfRuntime.programs[technique.program];
  102717. var states = technique.states;
  102718. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  102719. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  102720. var newVertexShader = "";
  102721. var newPixelShader = "";
  102722. var vertexTokenizer = new Tokenizer(vertexShader);
  102723. var pixelTokenizer = new Tokenizer(pixelShader);
  102724. var unTreatedUniforms = {};
  102725. var uniforms = [];
  102726. var attributes = [];
  102727. var samplers = [];
  102728. // Fill uniform, sampler2D and attributes
  102729. for (var unif in technique.uniforms) {
  102730. var uniform = technique.uniforms[unif];
  102731. var uniformParameter = technique.parameters[uniform];
  102732. unTreatedUniforms[unif] = uniformParameter;
  102733. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  102734. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  102735. if (transformIndex !== -1) {
  102736. uniforms.push(babylonTransforms[transformIndex]);
  102737. delete unTreatedUniforms[unif];
  102738. }
  102739. else {
  102740. uniforms.push(unif);
  102741. }
  102742. }
  102743. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  102744. samplers.push(unif);
  102745. }
  102746. else {
  102747. uniforms.push(unif);
  102748. }
  102749. }
  102750. for (var attr in technique.attributes) {
  102751. var attribute = technique.attributes[attr];
  102752. var attributeParameter = technique.parameters[attribute];
  102753. if (attributeParameter.semantic) {
  102754. attributes.push(getAttribute(attributeParameter));
  102755. }
  102756. }
  102757. // Configure vertex shader
  102758. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  102759. var tokenType = vertexTokenizer.currentToken;
  102760. if (tokenType !== ETokenType.IDENTIFIER) {
  102761. newVertexShader += vertexTokenizer.currentString;
  102762. continue;
  102763. }
  102764. var foundAttribute = false;
  102765. for (var attr in technique.attributes) {
  102766. var attribute = technique.attributes[attr];
  102767. var attributeParameter = technique.parameters[attribute];
  102768. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  102769. newVertexShader += getAttribute(attributeParameter);
  102770. foundAttribute = true;
  102771. break;
  102772. }
  102773. }
  102774. if (foundAttribute) {
  102775. continue;
  102776. }
  102777. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  102778. }
  102779. // Configure pixel shader
  102780. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  102781. var tokenType = pixelTokenizer.currentToken;
  102782. if (tokenType !== ETokenType.IDENTIFIER) {
  102783. newPixelShader += pixelTokenizer.currentString;
  102784. continue;
  102785. }
  102786. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  102787. }
  102788. // Create shader material
  102789. var shaderPath = {
  102790. vertex: program.vertexShader + id,
  102791. fragment: program.fragmentShader + id
  102792. };
  102793. var options = {
  102794. attributes: attributes,
  102795. uniforms: uniforms,
  102796. samplers: samplers,
  102797. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  102798. };
  102799. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  102800. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  102801. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  102802. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  102803. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  102804. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  102805. if (states && states.functions) {
  102806. var functions = states.functions;
  102807. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  102808. shaderMaterial.backFaceCulling = false;
  102809. }
  102810. var blendFunc = functions.blendFuncSeparate;
  102811. if (blendFunc) {
  102812. 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) {
  102813. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  102814. }
  102815. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102816. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  102817. }
  102818. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102819. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  102820. }
  102821. 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) {
  102822. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  102823. }
  102824. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  102825. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  102826. }
  102827. 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) {
  102828. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  102829. }
  102830. }
  102831. }
  102832. };
  102833. return GLTFLoaderBase;
  102834. }());
  102835. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  102836. /**
  102837. * glTF V1 Loader
  102838. */
  102839. var GLTFLoader = /** @class */ (function () {
  102840. function GLTFLoader() {
  102841. // #region Stubs for IGLTFLoader interface
  102842. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  102843. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  102844. this.compileMaterials = false;
  102845. this.useClipPlane = false;
  102846. this.compileShadowGenerators = false;
  102847. this.onDisposeObservable = new BABYLON.Observable();
  102848. this.onMeshLoadedObservable = new BABYLON.Observable();
  102849. this.onTextureLoadedObservable = new BABYLON.Observable();
  102850. this.onMaterialLoadedObservable = new BABYLON.Observable();
  102851. this.onCompleteObservable = new BABYLON.Observable();
  102852. this.onExtensionLoadedObservable = new BABYLON.Observable();
  102853. /**
  102854. * State of the loader
  102855. */
  102856. this.state = null;
  102857. }
  102858. GLTFLoader.RegisterExtension = function (extension) {
  102859. if (GLTFLoader.Extensions[extension.name]) {
  102860. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  102861. return;
  102862. }
  102863. GLTFLoader.Extensions[extension.name] = extension;
  102864. };
  102865. GLTFLoader.prototype.dispose = function () { };
  102866. // #endregion
  102867. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  102868. var _this = this;
  102869. scene.useRightHandedSystem = true;
  102870. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102871. gltfRuntime.importOnlyMeshes = true;
  102872. if (meshesNames === "") {
  102873. gltfRuntime.importMeshesNames = [];
  102874. }
  102875. else if (typeof meshesNames === "string") {
  102876. gltfRuntime.importMeshesNames = [meshesNames];
  102877. }
  102878. else if (meshesNames && !(meshesNames instanceof Array)) {
  102879. gltfRuntime.importMeshesNames = [meshesNames];
  102880. }
  102881. else {
  102882. gltfRuntime.importMeshesNames = [];
  102883. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  102884. }
  102885. // Create nodes
  102886. _this._createNodes(gltfRuntime);
  102887. var meshes = new Array();
  102888. var skeletons = new Array();
  102889. // Fill arrays of meshes and skeletons
  102890. for (var nde in gltfRuntime.nodes) {
  102891. var node = gltfRuntime.nodes[nde];
  102892. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  102893. meshes.push(node.babylonNode);
  102894. }
  102895. }
  102896. for (var skl in gltfRuntime.skins) {
  102897. var skin = gltfRuntime.skins[skl];
  102898. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  102899. skeletons.push(skin.babylonSkeleton);
  102900. }
  102901. }
  102902. // Load buffers, shaders, materials, etc.
  102903. _this._loadBuffersAsync(gltfRuntime, function () {
  102904. _this._loadShadersAsync(gltfRuntime, function () {
  102905. importMaterials(gltfRuntime);
  102906. postLoad(gltfRuntime);
  102907. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102908. onSuccess(meshes, skeletons);
  102909. }
  102910. });
  102911. }, onProgress);
  102912. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  102913. onSuccess(meshes, skeletons);
  102914. }
  102915. }, onError);
  102916. return true;
  102917. };
  102918. /**
  102919. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  102920. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  102921. * @param scene the scene the meshes should be added to
  102922. * @param data gltf data containing information of the meshes in a loaded file
  102923. * @param rootUrl root url to load from
  102924. * @param onProgress event that fires when loading progress has occured
  102925. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  102926. */
  102927. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  102928. var _this = this;
  102929. return new Promise(function (resolve, reject) {
  102930. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  102931. resolve({
  102932. meshes: meshes,
  102933. particleSystems: [],
  102934. skeletons: skeletons,
  102935. animationGroups: []
  102936. });
  102937. }, onProgress, function (message) {
  102938. reject(new Error(message));
  102939. });
  102940. });
  102941. };
  102942. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  102943. var _this = this;
  102944. scene.useRightHandedSystem = true;
  102945. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  102946. // Load runtime extensios
  102947. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  102948. // Create nodes
  102949. _this._createNodes(gltfRuntime);
  102950. // Load buffers, shaders, materials, etc.
  102951. _this._loadBuffersAsync(gltfRuntime, function () {
  102952. _this._loadShadersAsync(gltfRuntime, function () {
  102953. importMaterials(gltfRuntime);
  102954. postLoad(gltfRuntime);
  102955. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  102956. onSuccess();
  102957. }
  102958. });
  102959. });
  102960. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  102961. onSuccess();
  102962. }
  102963. }, onError);
  102964. }, onError);
  102965. };
  102966. /**
  102967. * Imports all objects from a loaded gltf file and adds them to the scene
  102968. * @param scene the scene the objects should be added to
  102969. * @param data gltf data containing information of the meshes in a loaded file
  102970. * @param rootUrl root url to load from
  102971. * @param onProgress event that fires when loading progress has occured
  102972. * @returns a promise which completes when objects have been loaded to the scene
  102973. */
  102974. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  102975. var _this = this;
  102976. return new Promise(function (resolve, reject) {
  102977. _this._loadAsync(scene, data, rootUrl, function () {
  102978. resolve();
  102979. }, onProgress, function (message) {
  102980. reject(new Error(message));
  102981. });
  102982. });
  102983. };
  102984. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  102985. var hasShaders = false;
  102986. var processShader = function (sha, shader) {
  102987. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  102988. if (shaderString instanceof ArrayBuffer) {
  102989. return;
  102990. }
  102991. gltfRuntime.loadedShaderCount++;
  102992. if (shaderString) {
  102993. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  102994. }
  102995. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  102996. onload();
  102997. }
  102998. }, function () {
  102999. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103000. });
  103001. };
  103002. for (var sha in gltfRuntime.shaders) {
  103003. hasShaders = true;
  103004. var shader = gltfRuntime.shaders[sha];
  103005. if (shader) {
  103006. processShader.bind(this, sha, shader)();
  103007. }
  103008. else {
  103009. BABYLON.Tools.Error("No shader named: " + sha);
  103010. }
  103011. }
  103012. if (!hasShaders) {
  103013. onload();
  103014. }
  103015. };
  103016. ;
  103017. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103018. var hasBuffers = false;
  103019. var processBuffer = function (buf, buffer) {
  103020. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103021. gltfRuntime.loadedBufferCount++;
  103022. if (bufferView) {
  103023. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103024. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103025. }
  103026. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103027. }
  103028. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103029. onLoad();
  103030. }
  103031. }, function () {
  103032. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103033. });
  103034. };
  103035. for (var buf in gltfRuntime.buffers) {
  103036. hasBuffers = true;
  103037. var buffer = gltfRuntime.buffers[buf];
  103038. if (buffer) {
  103039. processBuffer.bind(this, buf, buffer)();
  103040. }
  103041. else {
  103042. BABYLON.Tools.Error("No buffer named: " + buf);
  103043. }
  103044. }
  103045. if (!hasBuffers) {
  103046. onLoad();
  103047. }
  103048. };
  103049. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  103050. var currentScene = gltfRuntime.currentScene;
  103051. if (currentScene) {
  103052. // Only one scene even if multiple scenes are defined
  103053. for (var i = 0; i < currentScene.nodes.length; i++) {
  103054. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103055. }
  103056. }
  103057. else {
  103058. // Load all scenes
  103059. for (var thing in gltfRuntime.scenes) {
  103060. currentScene = gltfRuntime.scenes[thing];
  103061. for (var i = 0; i < currentScene.nodes.length; i++) {
  103062. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103063. }
  103064. }
  103065. }
  103066. };
  103067. GLTFLoader.Extensions = {};
  103068. return GLTFLoader;
  103069. }());
  103070. GLTF1.GLTFLoader = GLTFLoader;
  103071. ;
  103072. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  103073. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103074. })(BABYLON || (BABYLON = {}));
  103075. //# sourceMappingURL=babylon.glTFLoader.js.map
  103076. var BABYLON;
  103077. (function (BABYLON) {
  103078. var GLTF1;
  103079. (function (GLTF1) {
  103080. /**
  103081. * Utils functions for GLTF
  103082. */
  103083. var GLTFUtils = /** @class */ (function () {
  103084. function GLTFUtils() {
  103085. }
  103086. /**
  103087. * Sets the given "parameter" matrix
  103088. * @param scene: the {BABYLON.Scene} object
  103089. * @param source: the source node where to pick the matrix
  103090. * @param parameter: the GLTF technique parameter
  103091. * @param uniformName: the name of the shader's uniform
  103092. * @param shaderMaterial: the shader material
  103093. */
  103094. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  103095. var mat = null;
  103096. if (parameter.semantic === "MODEL") {
  103097. mat = source.getWorldMatrix();
  103098. }
  103099. else if (parameter.semantic === "PROJECTION") {
  103100. mat = scene.getProjectionMatrix();
  103101. }
  103102. else if (parameter.semantic === "VIEW") {
  103103. mat = scene.getViewMatrix();
  103104. }
  103105. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  103106. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  103107. }
  103108. else if (parameter.semantic === "MODELVIEW") {
  103109. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  103110. }
  103111. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  103112. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  103113. }
  103114. else if (parameter.semantic === "MODELINVERSE") {
  103115. mat = source.getWorldMatrix().invert();
  103116. }
  103117. else if (parameter.semantic === "VIEWINVERSE") {
  103118. mat = scene.getViewMatrix().invert();
  103119. }
  103120. else if (parameter.semantic === "PROJECTIONINVERSE") {
  103121. mat = scene.getProjectionMatrix().invert();
  103122. }
  103123. else if (parameter.semantic === "MODELVIEWINVERSE") {
  103124. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  103125. }
  103126. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  103127. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  103128. }
  103129. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  103130. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  103131. }
  103132. else {
  103133. debugger;
  103134. }
  103135. if (mat) {
  103136. switch (parameter.type) {
  103137. case GLTF1.EParameterType.FLOAT_MAT2:
  103138. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  103139. break;
  103140. case GLTF1.EParameterType.FLOAT_MAT3:
  103141. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  103142. break;
  103143. case GLTF1.EParameterType.FLOAT_MAT4:
  103144. shaderMaterial.setMatrix(uniformName, mat);
  103145. break;
  103146. default: break;
  103147. }
  103148. }
  103149. };
  103150. /**
  103151. * Sets the given "parameter" matrix
  103152. * @param shaderMaterial: the shader material
  103153. * @param uniform: the name of the shader's uniform
  103154. * @param value: the value of the uniform
  103155. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  103156. */
  103157. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  103158. switch (type) {
  103159. case GLTF1.EParameterType.FLOAT:
  103160. shaderMaterial.setFloat(uniform, value);
  103161. return true;
  103162. case GLTF1.EParameterType.FLOAT_VEC2:
  103163. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  103164. return true;
  103165. case GLTF1.EParameterType.FLOAT_VEC3:
  103166. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  103167. return true;
  103168. case GLTF1.EParameterType.FLOAT_VEC4:
  103169. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  103170. return true;
  103171. default: return false;
  103172. }
  103173. };
  103174. /**
  103175. * Returns the wrap mode of the texture
  103176. * @param mode: the mode value
  103177. */
  103178. GLTFUtils.GetWrapMode = function (mode) {
  103179. switch (mode) {
  103180. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  103181. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  103182. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103183. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103184. }
  103185. };
  103186. /**
  103187. * Returns the byte stride giving an accessor
  103188. * @param accessor: the GLTF accessor objet
  103189. */
  103190. GLTFUtils.GetByteStrideFromType = function (accessor) {
  103191. // Needs this function since "byteStride" isn't requiered in glTF format
  103192. var type = accessor.type;
  103193. switch (type) {
  103194. case "VEC2": return 2;
  103195. case "VEC3": return 3;
  103196. case "VEC4": return 4;
  103197. case "MAT2": return 4;
  103198. case "MAT3": return 9;
  103199. case "MAT4": return 16;
  103200. default: return 1;
  103201. }
  103202. };
  103203. /**
  103204. * Returns the texture filter mode giving a mode value
  103205. * @param mode: the filter mode value
  103206. */
  103207. GLTFUtils.GetTextureFilterMode = function (mode) {
  103208. switch (mode) {
  103209. case GLTF1.ETextureFilterType.LINEAR:
  103210. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  103211. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103212. case GLTF1.ETextureFilterType.NEAREST:
  103213. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  103214. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103215. }
  103216. };
  103217. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  103218. var byteOffset = bufferView.byteOffset + byteOffset;
  103219. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  103220. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  103221. throw new Error("Buffer access is out of range");
  103222. }
  103223. var buffer = loadedBufferView.buffer;
  103224. byteOffset += loadedBufferView.byteOffset;
  103225. switch (componentType) {
  103226. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  103227. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  103228. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  103229. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  103230. default: return new Float32Array(buffer, byteOffset, byteLength);
  103231. }
  103232. };
  103233. /**
  103234. * Returns a buffer from its accessor
  103235. * @param gltfRuntime: the GLTF runtime
  103236. * @param accessor: the GLTF accessor
  103237. */
  103238. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  103239. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  103240. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  103241. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  103242. };
  103243. /**
  103244. * Decodes a buffer view into a string
  103245. * @param view: the buffer view
  103246. */
  103247. GLTFUtils.DecodeBufferToText = function (view) {
  103248. var result = "";
  103249. var length = view.byteLength;
  103250. for (var i = 0; i < length; ++i) {
  103251. result += String.fromCharCode(view[i]);
  103252. }
  103253. return result;
  103254. };
  103255. /**
  103256. * Returns the default material of gltf. Related to
  103257. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  103258. * @param scene: the Babylon.js scene
  103259. */
  103260. GLTFUtils.GetDefaultMaterial = function (scene) {
  103261. if (!GLTFUtils._DefaultMaterial) {
  103262. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  103263. "precision highp float;",
  103264. "",
  103265. "uniform mat4 worldView;",
  103266. "uniform mat4 projection;",
  103267. "",
  103268. "attribute vec3 position;",
  103269. "",
  103270. "void main(void)",
  103271. "{",
  103272. " gl_Position = projection * worldView * vec4(position, 1.0);",
  103273. "}"
  103274. ].join("\n");
  103275. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  103276. "precision highp float;",
  103277. "",
  103278. "uniform vec4 u_emission;",
  103279. "",
  103280. "void main(void)",
  103281. "{",
  103282. " gl_FragColor = u_emission;",
  103283. "}"
  103284. ].join("\n");
  103285. var shaderPath = {
  103286. vertex: "GLTFDefaultMaterial",
  103287. fragment: "GLTFDefaultMaterial"
  103288. };
  103289. var options = {
  103290. attributes: ["position"],
  103291. uniforms: ["worldView", "projection", "u_emission"],
  103292. samplers: new Array(),
  103293. needAlphaBlending: false
  103294. };
  103295. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  103296. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  103297. }
  103298. return GLTFUtils._DefaultMaterial;
  103299. };
  103300. // The GLTF default material
  103301. GLTFUtils._DefaultMaterial = null;
  103302. return GLTFUtils;
  103303. }());
  103304. GLTF1.GLTFUtils = GLTFUtils;
  103305. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103306. })(BABYLON || (BABYLON = {}));
  103307. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  103308. var BABYLON;
  103309. (function (BABYLON) {
  103310. var GLTF1;
  103311. (function (GLTF1) {
  103312. var GLTFLoaderExtension = /** @class */ (function () {
  103313. function GLTFLoaderExtension(name) {
  103314. this._name = name;
  103315. }
  103316. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  103317. get: function () {
  103318. return this._name;
  103319. },
  103320. enumerable: true,
  103321. configurable: true
  103322. });
  103323. /**
  103324. * Defines an override for loading the runtime
  103325. * Return true to stop further extensions from loading the runtime
  103326. */
  103327. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103328. return false;
  103329. };
  103330. /**
  103331. * Defines an onverride for creating gltf runtime
  103332. * Return true to stop further extensions from creating the runtime
  103333. */
  103334. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103335. return false;
  103336. };
  103337. /**
  103338. * Defines an override for loading buffers
  103339. * Return true to stop further extensions from loading this buffer
  103340. */
  103341. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103342. return false;
  103343. };
  103344. /**
  103345. * Defines an override for loading texture buffers
  103346. * Return true to stop further extensions from loading this texture data
  103347. */
  103348. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103349. return false;
  103350. };
  103351. /**
  103352. * Defines an override for creating textures
  103353. * Return true to stop further extensions from loading this texture
  103354. */
  103355. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103356. return false;
  103357. };
  103358. /**
  103359. * Defines an override for loading shader strings
  103360. * Return true to stop further extensions from loading this shader data
  103361. */
  103362. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103363. return false;
  103364. };
  103365. /**
  103366. * Defines an override for loading materials
  103367. * Return true to stop further extensions from loading this material
  103368. */
  103369. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103370. return false;
  103371. };
  103372. // ---------
  103373. // Utilities
  103374. // ---------
  103375. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103376. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103377. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  103378. }, function () {
  103379. setTimeout(function () {
  103380. if (!onSuccess) {
  103381. return;
  103382. }
  103383. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103384. });
  103385. });
  103386. };
  103387. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103388. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103389. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  103390. }, function () {
  103391. setTimeout(function () {
  103392. onSuccess();
  103393. });
  103394. });
  103395. };
  103396. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103397. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103398. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103399. }, function () {
  103400. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  103401. });
  103402. };
  103403. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  103404. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103405. if (buffer) {
  103406. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103407. }
  103408. }, onError);
  103409. };
  103410. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103411. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103412. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103413. }, function () {
  103414. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  103415. });
  103416. };
  103417. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103418. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103419. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103420. }, function () {
  103421. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  103422. });
  103423. };
  103424. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103425. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103426. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103427. }, function () {
  103428. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  103429. });
  103430. };
  103431. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103432. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  103433. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103434. }, function () {
  103435. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  103436. });
  103437. };
  103438. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  103439. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  103440. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  103441. if (func(loaderExtension)) {
  103442. return;
  103443. }
  103444. }
  103445. defaultFunc();
  103446. };
  103447. return GLTFLoaderExtension;
  103448. }());
  103449. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  103450. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103451. })(BABYLON || (BABYLON = {}));
  103452. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  103453. var BABYLON;
  103454. (function (BABYLON) {
  103455. var GLTF1;
  103456. (function (GLTF1) {
  103457. var BinaryExtensionBufferName = "binary_glTF";
  103458. ;
  103459. ;
  103460. var GLTFBinaryExtension = /** @class */ (function (_super) {
  103461. __extends(GLTFBinaryExtension, _super);
  103462. function GLTFBinaryExtension() {
  103463. return _super.call(this, "KHR_binary_glTF") || this;
  103464. }
  103465. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103466. var extensionsUsed = data.json.extensionsUsed;
  103467. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  103468. return false;
  103469. }
  103470. this._bin = data.bin;
  103471. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  103472. return true;
  103473. };
  103474. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103475. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  103476. return false;
  103477. }
  103478. if (id !== BinaryExtensionBufferName) {
  103479. return false;
  103480. }
  103481. onSuccess(this._bin);
  103482. return true;
  103483. };
  103484. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103485. var texture = gltfRuntime.textures[id];
  103486. var source = gltfRuntime.images[texture.source];
  103487. if (!source.extensions || !(this.name in source.extensions)) {
  103488. return false;
  103489. }
  103490. var sourceExt = source.extensions[this.name];
  103491. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  103492. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103493. onSuccess(buffer);
  103494. return true;
  103495. };
  103496. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103497. var shader = gltfRuntime.shaders[id];
  103498. if (!shader.extensions || !(this.name in shader.extensions)) {
  103499. return false;
  103500. }
  103501. var binaryExtensionShader = shader.extensions[this.name];
  103502. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  103503. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  103504. setTimeout(function () {
  103505. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  103506. onSuccess(shaderString);
  103507. });
  103508. return true;
  103509. };
  103510. return GLTFBinaryExtension;
  103511. }(GLTF1.GLTFLoaderExtension));
  103512. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  103513. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  103514. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103515. })(BABYLON || (BABYLON = {}));
  103516. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  103517. var BABYLON;
  103518. (function (BABYLON) {
  103519. var GLTF1;
  103520. (function (GLTF1) {
  103521. ;
  103522. ;
  103523. ;
  103524. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  103525. __extends(GLTFMaterialsCommonExtension, _super);
  103526. function GLTFMaterialsCommonExtension() {
  103527. return _super.call(this, "KHR_materials_common") || this;
  103528. }
  103529. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103530. if (!gltfRuntime.extensions)
  103531. return false;
  103532. var extension = gltfRuntime.extensions[this.name];
  103533. if (!extension)
  103534. return false;
  103535. // Create lights
  103536. var lights = extension.lights;
  103537. if (lights) {
  103538. for (var thing in lights) {
  103539. var light = lights[thing];
  103540. switch (light.type) {
  103541. case "ambient":
  103542. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  103543. var ambient = light.ambient;
  103544. if (ambient) {
  103545. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  103546. }
  103547. break;
  103548. case "point":
  103549. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  103550. var point = light.point;
  103551. if (point) {
  103552. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  103553. }
  103554. break;
  103555. case "directional":
  103556. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  103557. var directional = light.directional;
  103558. if (directional) {
  103559. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  103560. }
  103561. break;
  103562. case "spot":
  103563. var spot = light.spot;
  103564. if (spot) {
  103565. 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);
  103566. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  103567. }
  103568. break;
  103569. default:
  103570. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  103571. break;
  103572. }
  103573. }
  103574. }
  103575. return false;
  103576. };
  103577. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103578. var material = gltfRuntime.materials[id];
  103579. if (!material || !material.extensions)
  103580. return false;
  103581. var extension = material.extensions[this.name];
  103582. if (!extension)
  103583. return false;
  103584. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103585. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103586. if (extension.technique === "CONSTANT") {
  103587. standardMaterial.disableLighting = true;
  103588. }
  103589. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  103590. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  103591. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  103592. // Ambient
  103593. if (typeof extension.values.ambient === "string") {
  103594. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  103595. }
  103596. else {
  103597. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  103598. }
  103599. // Diffuse
  103600. if (typeof extension.values.diffuse === "string") {
  103601. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  103602. }
  103603. else {
  103604. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  103605. }
  103606. // Emission
  103607. if (typeof extension.values.emission === "string") {
  103608. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  103609. }
  103610. else {
  103611. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  103612. }
  103613. // Specular
  103614. if (typeof extension.values.specular === "string") {
  103615. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  103616. }
  103617. else {
  103618. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  103619. }
  103620. return true;
  103621. };
  103622. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  103623. // Create buffer from texture url
  103624. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  103625. // Create texture from buffer
  103626. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  103627. }, onError);
  103628. };
  103629. return GLTFMaterialsCommonExtension;
  103630. }(GLTF1.GLTFLoaderExtension));
  103631. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  103632. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  103633. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103634. })(BABYLON || (BABYLON = {}));
  103635. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  103636. var BABYLON;
  103637. (function (BABYLON) {
  103638. var GLTF2;
  103639. (function (GLTF2) {
  103640. /** Array item helper methods */
  103641. var ArrayItem = /** @class */ (function () {
  103642. function ArrayItem() {
  103643. }
  103644. /** Sets the index of each array element to its index in the array */
  103645. ArrayItem.Assign = function (values) {
  103646. if (values) {
  103647. for (var index = 0; index < values.length; index++) {
  103648. values[index]._index = index;
  103649. }
  103650. }
  103651. };
  103652. return ArrayItem;
  103653. }());
  103654. GLTF2.ArrayItem = ArrayItem;
  103655. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  103656. })(BABYLON || (BABYLON = {}));
  103657. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  103658. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103659. /**
  103660. * Defines the GLTF2 module used to import/export GLTF 2.0 files
  103661. */
  103662. var BABYLON;
  103663. (function (BABYLON) {
  103664. var GLTF2;
  103665. (function (GLTF2) {
  103666. /**
  103667. * Used to load from a GLTF2 file
  103668. */
  103669. var GLTFLoader = /** @class */ (function () {
  103670. function GLTFLoader() {
  103671. /**
  103672. * @ignore
  103673. */
  103674. this._completePromises = new Array();
  103675. this._disposed = false;
  103676. this._state = null;
  103677. this._extensions = {};
  103678. this._defaultSampler = {};
  103679. this._defaultBabylonMaterials = {};
  103680. this._requests = new Array();
  103681. /**
  103682. * Coordinate system that will be used when loading from the gltf file
  103683. */
  103684. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103685. /**
  103686. * Animation mode that determines which animations should be started when a file is loaded
  103687. */
  103688. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103689. /**
  103690. * If the materials in the file should automatically be compiled
  103691. */
  103692. this.compileMaterials = false;
  103693. /**
  103694. * If a clip plane should be usede when loading meshes in the file
  103695. */
  103696. this.useClipPlane = false;
  103697. /**
  103698. * If shadow generators should automatically be compiled
  103699. */
  103700. this.compileShadowGenerators = false;
  103701. /**
  103702. * Observable that fires when the loader is disposed
  103703. */
  103704. this.onDisposeObservable = new BABYLON.Observable();
  103705. /**
  103706. * Observable that fires each time a mesh is loaded
  103707. */
  103708. this.onMeshLoadedObservable = new BABYLON.Observable();
  103709. /**
  103710. * Observable that fires each time a texture is loaded
  103711. */
  103712. this.onTextureLoadedObservable = new BABYLON.Observable();
  103713. /**
  103714. * Observable that fires each time a material is loaded
  103715. */
  103716. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103717. /**
  103718. * Observable that fires each time an extension is loaded
  103719. */
  103720. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103721. /**
  103722. * Observable that fires when the load has completed
  103723. */
  103724. this.onCompleteObservable = new BABYLON.Observable();
  103725. }
  103726. /**
  103727. * @ignore, registers the loader
  103728. * @param name name of the loader
  103729. * @param factory function that converts a loader to a loader extension
  103730. */
  103731. GLTFLoader._Register = function (name, factory) {
  103732. if (GLTFLoader._Factories[name]) {
  103733. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  103734. return;
  103735. }
  103736. GLTFLoader._Factories[name] = factory;
  103737. // Keep the order of registration so that extensions registered first are called first.
  103738. GLTFLoader._Names.push(name);
  103739. };
  103740. Object.defineProperty(GLTFLoader.prototype, "state", {
  103741. /**
  103742. * The current state of the loader
  103743. */
  103744. get: function () {
  103745. return this._state;
  103746. },
  103747. enumerable: true,
  103748. configurable: true
  103749. });
  103750. /**
  103751. * Disposes of the loader
  103752. */
  103753. GLTFLoader.prototype.dispose = function () {
  103754. if (this._disposed) {
  103755. return;
  103756. }
  103757. this._disposed = true;
  103758. this.onDisposeObservable.notifyObservers(this);
  103759. this.onDisposeObservable.clear();
  103760. this._clear();
  103761. };
  103762. /**
  103763. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103764. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103765. * @param scene the scene the meshes should be added to
  103766. * @param data gltf data containing information of the meshes in a loaded file
  103767. * @param rootUrl root url to load from
  103768. * @param onProgress event that fires when loading progress has occured
  103769. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103770. */
  103771. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103772. var _this = this;
  103773. return Promise.resolve().then(function () {
  103774. var nodes = null;
  103775. if (meshesNames) {
  103776. var nodeMap_1 = {};
  103777. if (_this._gltf.nodes) {
  103778. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  103779. var node = _a[_i];
  103780. if (node.name) {
  103781. nodeMap_1[node.name] = node;
  103782. }
  103783. }
  103784. }
  103785. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  103786. nodes = names.map(function (name) {
  103787. var node = nodeMap_1[name];
  103788. if (!node) {
  103789. throw new Error("Failed to find node '" + name + "'");
  103790. }
  103791. return node;
  103792. });
  103793. }
  103794. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  103795. return {
  103796. meshes: _this._getMeshes(),
  103797. particleSystems: [],
  103798. skeletons: _this._getSkeletons(),
  103799. animationGroups: _this._getAnimationGroups()
  103800. };
  103801. });
  103802. });
  103803. };
  103804. /**
  103805. * Imports all objects from a loaded gltf file and adds them to the scene
  103806. * @param scene the scene the objects should be added to
  103807. * @param data gltf data containing information of the meshes in a loaded file
  103808. * @param rootUrl root url to load from
  103809. * @param onProgress event that fires when loading progress has occured
  103810. * @returns a promise which completes when objects have been loaded to the scene
  103811. */
  103812. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103813. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  103814. };
  103815. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  103816. var _this = this;
  103817. return Promise.resolve().then(function () {
  103818. _this._loadExtensions();
  103819. _this._babylonScene = scene;
  103820. _this._rootUrl = rootUrl;
  103821. _this._progressCallback = onProgress;
  103822. _this._state = BABYLON.GLTFLoaderState.LOADING;
  103823. _this._loadData(data);
  103824. _this._checkExtensions();
  103825. var promises = new Array();
  103826. if (nodes) {
  103827. promises.push(_this._loadNodesAsync(nodes));
  103828. }
  103829. else {
  103830. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  103831. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  103832. }
  103833. if (_this.compileMaterials) {
  103834. promises.push(_this._compileMaterialsAsync());
  103835. }
  103836. if (_this.compileShadowGenerators) {
  103837. promises.push(_this._compileShadowGeneratorsAsync());
  103838. }
  103839. var resultPromise = Promise.all(promises).then(function () {
  103840. _this._state = BABYLON.GLTFLoaderState.READY;
  103841. _this._startAnimations();
  103842. });
  103843. resultPromise.then(function () {
  103844. _this._rootBabylonMesh.setEnabled(true);
  103845. BABYLON.Tools.SetImmediate(function () {
  103846. if (!_this._disposed) {
  103847. Promise.all(_this._completePromises).then(function () {
  103848. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  103849. _this.onCompleteObservable.notifyObservers(_this);
  103850. _this.onCompleteObservable.clear();
  103851. _this._clear();
  103852. }).catch(function (error) {
  103853. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103854. _this._clear();
  103855. });
  103856. }
  103857. });
  103858. });
  103859. return resultPromise;
  103860. }).catch(function (error) {
  103861. BABYLON.Tools.Error("glTF Loader: " + error.message);
  103862. _this._clear();
  103863. throw error;
  103864. });
  103865. };
  103866. GLTFLoader.prototype._loadExtensions = function () {
  103867. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  103868. var name_1 = _a[_i];
  103869. var extension = GLTFLoader._Factories[name_1](this);
  103870. this._extensions[name_1] = extension;
  103871. this.onExtensionLoadedObservable.notifyObservers(extension);
  103872. }
  103873. this.onExtensionLoadedObservable.clear();
  103874. };
  103875. GLTFLoader.prototype._loadData = function (data) {
  103876. this._gltf = data.json;
  103877. this._setupData();
  103878. if (data.bin) {
  103879. var buffers = this._gltf.buffers;
  103880. if (buffers && buffers[0] && !buffers[0].uri) {
  103881. var binaryBuffer = buffers[0];
  103882. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  103883. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  103884. }
  103885. binaryBuffer._data = Promise.resolve(data.bin);
  103886. }
  103887. else {
  103888. BABYLON.Tools.Warn("Unexpected BIN chunk");
  103889. }
  103890. }
  103891. };
  103892. GLTFLoader.prototype._setupData = function () {
  103893. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  103894. GLTF2.ArrayItem.Assign(this._gltf.animations);
  103895. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  103896. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  103897. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  103898. GLTF2.ArrayItem.Assign(this._gltf.images);
  103899. GLTF2.ArrayItem.Assign(this._gltf.materials);
  103900. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  103901. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  103902. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  103903. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  103904. GLTF2.ArrayItem.Assign(this._gltf.skins);
  103905. GLTF2.ArrayItem.Assign(this._gltf.textures);
  103906. if (this._gltf.nodes) {
  103907. var nodeParents = {};
  103908. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  103909. var node = _a[_i];
  103910. if (node.children) {
  103911. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  103912. var index = _c[_b];
  103913. nodeParents[index] = node._index;
  103914. }
  103915. }
  103916. }
  103917. var rootNode = this._createRootNode();
  103918. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  103919. var node = _e[_d];
  103920. var parentIndex = nodeParents[node._index];
  103921. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  103922. }
  103923. }
  103924. };
  103925. GLTFLoader.prototype._checkExtensions = function () {
  103926. if (this._gltf.extensionsRequired) {
  103927. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  103928. var name_2 = _a[_i];
  103929. var extension = this._extensions[name_2];
  103930. if (!extension || !extension.enabled) {
  103931. throw new Error("Require extension " + name_2 + " is not available");
  103932. }
  103933. }
  103934. }
  103935. };
  103936. GLTFLoader.prototype._createRootNode = function () {
  103937. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  103938. this._rootBabylonMesh.setEnabled(false);
  103939. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  103940. switch (this.coordinateSystemMode) {
  103941. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  103942. if (!this._babylonScene.useRightHandedSystem) {
  103943. rootNode.rotation = [0, 1, 0, 0];
  103944. rootNode.scale = [1, 1, -1];
  103945. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  103946. }
  103947. break;
  103948. }
  103949. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  103950. this._babylonScene.useRightHandedSystem = true;
  103951. break;
  103952. }
  103953. default: {
  103954. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  103955. }
  103956. }
  103957. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  103958. return rootNode;
  103959. };
  103960. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  103961. var promises = new Array();
  103962. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  103963. var node = nodes_1[_i];
  103964. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103965. }
  103966. promises.push(this._loadAnimationsAsync());
  103967. return Promise.all(promises).then(function () { });
  103968. };
  103969. /**
  103970. * @ignore
  103971. */
  103972. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  103973. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  103974. if (promise) {
  103975. return promise;
  103976. }
  103977. var promises = new Array();
  103978. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  103979. var index = _a[_i];
  103980. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  103981. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  103982. }
  103983. promises.push(this._loadAnimationsAsync());
  103984. return Promise.all(promises).then(function () { });
  103985. };
  103986. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  103987. if (node._primitiveBabylonMeshes) {
  103988. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  103989. var babylonMesh = _a[_i];
  103990. callback(babylonMesh);
  103991. }
  103992. }
  103993. else {
  103994. callback(node._babylonMesh);
  103995. }
  103996. };
  103997. GLTFLoader.prototype._getMeshes = function () {
  103998. var meshes = new Array();
  103999. // Root mesh is always first.
  104000. meshes.push(this._rootBabylonMesh);
  104001. var nodes = this._gltf.nodes;
  104002. if (nodes) {
  104003. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104004. var node = nodes_2[_i];
  104005. if (node._babylonMesh) {
  104006. meshes.push(node._babylonMesh);
  104007. }
  104008. if (node._primitiveBabylonMeshes) {
  104009. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104010. var babylonMesh = _b[_a];
  104011. meshes.push(babylonMesh);
  104012. }
  104013. }
  104014. }
  104015. }
  104016. return meshes;
  104017. };
  104018. GLTFLoader.prototype._getSkeletons = function () {
  104019. var skeletons = new Array();
  104020. var skins = this._gltf.skins;
  104021. if (skins) {
  104022. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104023. var skin = skins_1[_i];
  104024. if (skin._babylonSkeleton) {
  104025. skeletons.push(skin._babylonSkeleton);
  104026. }
  104027. }
  104028. }
  104029. return skeletons;
  104030. };
  104031. GLTFLoader.prototype._getAnimationGroups = function () {
  104032. var animationGroups = new Array();
  104033. var animations = this._gltf.animations;
  104034. if (animations) {
  104035. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104036. var animation = animations_1[_i];
  104037. if (animation._babylonAnimationGroup) {
  104038. animationGroups.push(animation._babylonAnimationGroup);
  104039. }
  104040. }
  104041. }
  104042. return animationGroups;
  104043. };
  104044. GLTFLoader.prototype._startAnimations = function () {
  104045. switch (this.animationStartMode) {
  104046. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  104047. // do nothing
  104048. break;
  104049. }
  104050. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  104051. var babylonAnimationGroups = this._getAnimationGroups();
  104052. if (babylonAnimationGroups.length !== 0) {
  104053. babylonAnimationGroups[0].start(true);
  104054. }
  104055. break;
  104056. }
  104057. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  104058. var babylonAnimationGroups = this._getAnimationGroups();
  104059. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  104060. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  104061. babylonAnimationGroup.start(true);
  104062. }
  104063. break;
  104064. }
  104065. default: {
  104066. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  104067. return;
  104068. }
  104069. }
  104070. };
  104071. /**
  104072. * @ignore
  104073. */
  104074. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  104075. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  104076. if (promise) {
  104077. return promise;
  104078. }
  104079. if (node._babylonMesh) {
  104080. throw new Error(context + ": Invalid recursive node hierarchy");
  104081. }
  104082. var promises = new Array();
  104083. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  104084. node._babylonMesh = babylonMesh;
  104085. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  104086. node._babylonAnimationTargets.push(babylonMesh);
  104087. GLTFLoader._LoadTransform(node, babylonMesh);
  104088. if (node.mesh != undefined) {
  104089. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  104090. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  104091. }
  104092. if (node.children) {
  104093. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  104094. var index = _a[_i];
  104095. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  104096. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  104097. }
  104098. }
  104099. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104100. return Promise.all(promises).then(function () { });
  104101. };
  104102. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  104103. var _this = this;
  104104. var promises = new Array();
  104105. var primitives = mesh.primitives;
  104106. if (!primitives || primitives.length === 0) {
  104107. throw new Error(context + ": Primitives are missing");
  104108. }
  104109. GLTF2.ArrayItem.Assign(primitives);
  104110. if (primitives.length === 1) {
  104111. var primitive = primitives[0];
  104112. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  104113. }
  104114. else {
  104115. node._primitiveBabylonMeshes = [];
  104116. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  104117. var primitive = primitives_1[_i];
  104118. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  104119. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  104120. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  104121. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104122. }
  104123. }
  104124. if (node.skin != undefined) {
  104125. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  104126. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  104127. }
  104128. return Promise.all(promises).then(function () {
  104129. _this._forEachPrimitive(node, function (babylonMesh) {
  104130. babylonMesh._refreshBoundingInfo(true);
  104131. });
  104132. });
  104133. };
  104134. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  104135. var _this = this;
  104136. var promises = new Array();
  104137. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  104138. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  104139. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  104140. babylonGeometry.applyToMesh(babylonMesh);
  104141. });
  104142. }));
  104143. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  104144. if (primitive.material == undefined) {
  104145. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  104146. }
  104147. else {
  104148. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  104149. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  104150. babylonMesh.material = babylonMaterial;
  104151. }));
  104152. }
  104153. return Promise.all(promises).then(function () { });
  104154. };
  104155. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104156. var _this = this;
  104157. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  104158. if (promise) {
  104159. return promise;
  104160. }
  104161. var attributes = primitive.attributes;
  104162. if (!attributes) {
  104163. throw new Error(context + ": Attributes are missing");
  104164. }
  104165. var promises = new Array();
  104166. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  104167. if (primitive.indices == undefined) {
  104168. babylonMesh.isUnIndexed = true;
  104169. }
  104170. else {
  104171. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  104172. promises.push(this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104173. babylonGeometry.setIndices(data);
  104174. }));
  104175. }
  104176. var loadAttribute = function (attribute, kind, callback) {
  104177. if (attributes[attribute] == undefined) {
  104178. return;
  104179. }
  104180. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104181. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104182. babylonMesh._delayInfo.push(kind);
  104183. }
  104184. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104185. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  104186. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  104187. }));
  104188. if (callback) {
  104189. callback(accessor);
  104190. }
  104191. };
  104192. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104193. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104194. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104195. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104196. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104197. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104198. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104199. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  104200. if (accessor.type === "VEC4" /* VEC4 */) {
  104201. babylonMesh.hasVertexAlpha = true;
  104202. }
  104203. });
  104204. return Promise.all(promises).then(function () {
  104205. return babylonGeometry;
  104206. });
  104207. };
  104208. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  104209. if (!primitive.targets) {
  104210. return;
  104211. }
  104212. if (node._numMorphTargets == undefined) {
  104213. node._numMorphTargets = primitive.targets.length;
  104214. }
  104215. else if (primitive.targets.length !== node._numMorphTargets) {
  104216. throw new Error(context + ": Primitives do not have the same number of targets");
  104217. }
  104218. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  104219. for (var index = 0; index < primitive.targets.length; index++) {
  104220. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  104221. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  104222. // TODO: tell the target whether it has positions, normals, tangents
  104223. }
  104224. };
  104225. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  104226. if (!primitive.targets) {
  104227. return Promise.resolve();
  104228. }
  104229. var promises = new Array();
  104230. var morphTargetManager = babylonMesh.morphTargetManager;
  104231. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  104232. var babylonMorphTarget = morphTargetManager.getTarget(index);
  104233. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  104234. }
  104235. return Promise.all(promises).then(function () { });
  104236. };
  104237. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  104238. var _this = this;
  104239. var promises = new Array();
  104240. var loadAttribute = function (attribute, kind, setData) {
  104241. if (attributes[attribute] == undefined) {
  104242. return;
  104243. }
  104244. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  104245. if (!babylonVertexBuffer) {
  104246. return;
  104247. }
  104248. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104249. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104250. if (!(data instanceof Float32Array)) {
  104251. throw new Error(context + ": Morph target accessor must have float data");
  104252. }
  104253. setData(babylonVertexBuffer, data);
  104254. }));
  104255. };
  104256. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  104257. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104258. data[index] += value;
  104259. });
  104260. babylonMorphTarget.setPositions(data);
  104261. });
  104262. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  104263. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104264. data[index] += value;
  104265. });
  104266. babylonMorphTarget.setNormals(data);
  104267. });
  104268. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  104269. var dataIndex = 0;
  104270. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104271. // Tangent data for morph targets is stored as xyz delta.
  104272. // The vertexData.tangent is stored as xyzw.
  104273. // So we need to skip every fourth vertexData.tangent.
  104274. if (((index + 1) % 4) !== 0) {
  104275. data[dataIndex++] += value;
  104276. }
  104277. });
  104278. babylonMorphTarget.setTangents(data);
  104279. });
  104280. return Promise.all(promises).then(function () { });
  104281. };
  104282. GLTFLoader._LoadTransform = function (node, babylonNode) {
  104283. var position = BABYLON.Vector3.Zero();
  104284. var rotation = BABYLON.Quaternion.Identity();
  104285. var scaling = BABYLON.Vector3.One();
  104286. if (node.matrix) {
  104287. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  104288. matrix.decompose(scaling, rotation, position);
  104289. }
  104290. else {
  104291. if (node.translation)
  104292. position = BABYLON.Vector3.FromArray(node.translation);
  104293. if (node.rotation)
  104294. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  104295. if (node.scale)
  104296. scaling = BABYLON.Vector3.FromArray(node.scale);
  104297. }
  104298. babylonNode.position = position;
  104299. babylonNode.rotationQuaternion = rotation;
  104300. babylonNode.scaling = scaling;
  104301. };
  104302. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  104303. var _this = this;
  104304. var assignSkeleton = function (skeleton) {
  104305. _this._forEachPrimitive(node, function (babylonMesh) {
  104306. babylonMesh.skeleton = skeleton;
  104307. });
  104308. // Ignore the TRS of skinned nodes.
  104309. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104310. node._babylonMesh.parent = _this._rootBabylonMesh;
  104311. node._babylonMesh.position = BABYLON.Vector3.Zero();
  104312. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  104313. node._babylonMesh.scaling = BABYLON.Vector3.One();
  104314. };
  104315. if (skin._loaded) {
  104316. return skin._loaded.then(function () {
  104317. assignSkeleton(skin._babylonSkeleton);
  104318. });
  104319. }
  104320. var skeletonId = "skeleton" + skin._index;
  104321. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  104322. skin._babylonSkeleton = babylonSkeleton;
  104323. this._loadBones(context, skin);
  104324. assignSkeleton(babylonSkeleton);
  104325. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  104326. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  104327. }));
  104328. };
  104329. GLTFLoader.prototype._loadBones = function (context, skin) {
  104330. var babylonBones = {};
  104331. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  104332. var index = _a[_i];
  104333. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  104334. this._loadBone(node, skin, babylonBones);
  104335. }
  104336. };
  104337. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  104338. var babylonBone = babylonBones[node._index];
  104339. if (babylonBone) {
  104340. return babylonBone;
  104341. }
  104342. var babylonParentBone = null;
  104343. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  104344. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  104345. }
  104346. var boneIndex = skin.joints.indexOf(node._index);
  104347. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  104348. babylonBones[node._index] = babylonBone;
  104349. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  104350. node._babylonAnimationTargets.push(babylonBone);
  104351. return babylonBone;
  104352. };
  104353. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  104354. if (skin.inverseBindMatrices == undefined) {
  104355. return Promise.resolve(null);
  104356. }
  104357. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  104358. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104359. return data;
  104360. });
  104361. };
  104362. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  104363. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  104364. var babylonBone = _a[_i];
  104365. var baseMatrix = BABYLON.Matrix.Identity();
  104366. var boneIndex = babylonBone._index;
  104367. if (inverseBindMatricesData && boneIndex !== -1) {
  104368. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  104369. baseMatrix.invertToRef(baseMatrix);
  104370. }
  104371. var babylonParentBone = babylonBone.getParent();
  104372. if (babylonParentBone) {
  104373. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  104374. }
  104375. babylonBone.updateMatrix(baseMatrix, false, false);
  104376. babylonBone._updateDifferenceMatrix(undefined, false);
  104377. }
  104378. };
  104379. GLTFLoader.prototype._getNodeMatrix = function (node) {
  104380. return node.matrix ?
  104381. BABYLON.Matrix.FromArray(node.matrix) :
  104382. 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());
  104383. };
  104384. GLTFLoader.prototype._loadAnimationsAsync = function () {
  104385. var animations = this._gltf.animations;
  104386. if (!animations) {
  104387. return Promise.resolve();
  104388. }
  104389. var promises = new Array();
  104390. for (var index = 0; index < animations.length; index++) {
  104391. var animation = animations[index];
  104392. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  104393. }
  104394. return Promise.all(promises).then(function () { });
  104395. };
  104396. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  104397. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  104398. animation._babylonAnimationGroup = babylonAnimationGroup;
  104399. var promises = new Array();
  104400. GLTF2.ArrayItem.Assign(animation.channels);
  104401. GLTF2.ArrayItem.Assign(animation.samplers);
  104402. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  104403. var channel = _a[_i];
  104404. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  104405. }
  104406. return Promise.all(promises).then(function () {
  104407. babylonAnimationGroup.normalize();
  104408. });
  104409. };
  104410. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  104411. var _this = this;
  104412. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  104413. if (!targetNode._babylonMesh) {
  104414. return Promise.resolve();
  104415. }
  104416. // Ignore animations targeting TRS of skinned nodes.
  104417. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104418. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  104419. return Promise.resolve();
  104420. }
  104421. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  104422. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  104423. var targetPath;
  104424. var animationType;
  104425. switch (channel.target.path) {
  104426. case "translation" /* TRANSLATION */: {
  104427. targetPath = "position";
  104428. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104429. break;
  104430. }
  104431. case "rotation" /* ROTATION */: {
  104432. targetPath = "rotationQuaternion";
  104433. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  104434. break;
  104435. }
  104436. case "scale" /* SCALE */: {
  104437. targetPath = "scaling";
  104438. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  104439. break;
  104440. }
  104441. case "weights" /* WEIGHTS */: {
  104442. targetPath = "influence";
  104443. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  104444. break;
  104445. }
  104446. default: {
  104447. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  104448. }
  104449. }
  104450. var outputBufferOffset = 0;
  104451. var getNextOutputValue;
  104452. switch (targetPath) {
  104453. case "position": {
  104454. getNextOutputValue = function () {
  104455. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104456. outputBufferOffset += 3;
  104457. return value;
  104458. };
  104459. break;
  104460. }
  104461. case "rotationQuaternion": {
  104462. getNextOutputValue = function () {
  104463. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  104464. outputBufferOffset += 4;
  104465. return value;
  104466. };
  104467. break;
  104468. }
  104469. case "scaling": {
  104470. getNextOutputValue = function () {
  104471. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  104472. outputBufferOffset += 3;
  104473. return value;
  104474. };
  104475. break;
  104476. }
  104477. case "influence": {
  104478. getNextOutputValue = function () {
  104479. var value = new Array(targetNode._numMorphTargets);
  104480. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  104481. value[i] = data.output[outputBufferOffset++];
  104482. }
  104483. return value;
  104484. };
  104485. break;
  104486. }
  104487. }
  104488. var getNextKey;
  104489. switch (data.interpolation) {
  104490. case "STEP" /* STEP */: {
  104491. getNextKey = function (frameIndex) { return ({
  104492. frame: data.input[frameIndex],
  104493. value: getNextOutputValue(),
  104494. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  104495. }); };
  104496. break;
  104497. }
  104498. case "LINEAR" /* LINEAR */: {
  104499. getNextKey = function (frameIndex) { return ({
  104500. frame: data.input[frameIndex],
  104501. value: getNextOutputValue()
  104502. }); };
  104503. break;
  104504. }
  104505. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104506. getNextKey = function (frameIndex) { return ({
  104507. frame: data.input[frameIndex],
  104508. inTangent: getNextOutputValue(),
  104509. value: getNextOutputValue(),
  104510. outTangent: getNextOutputValue()
  104511. }); };
  104512. break;
  104513. }
  104514. }
  104515. var keys = new Array(data.input.length);
  104516. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  104517. keys[frameIndex] = getNextKey(frameIndex);
  104518. }
  104519. if (targetPath === "influence") {
  104520. var _loop_1 = function (targetIndex) {
  104521. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104522. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104523. babylonAnimation.setKeys(keys.map(function (key) { return ({
  104524. frame: key.frame,
  104525. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  104526. value: key.value[targetIndex],
  104527. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  104528. }); }));
  104529. var morphTargets = new Array();
  104530. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  104531. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  104532. morphTarget.animations.push(babylonAnimation);
  104533. morphTargets.push(morphTarget);
  104534. });
  104535. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTargets);
  104536. };
  104537. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  104538. _loop_1(targetIndex);
  104539. }
  104540. }
  104541. else {
  104542. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  104543. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  104544. babylonAnimation.setKeys(keys);
  104545. if (targetNode._babylonAnimationTargets) {
  104546. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  104547. var babylonAnimationTarget = _a[_i];
  104548. babylonAnimationTarget.animations.push(babylonAnimation);
  104549. }
  104550. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonAnimationTargets);
  104551. }
  104552. }
  104553. });
  104554. };
  104555. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  104556. if (sampler._data) {
  104557. return sampler._data;
  104558. }
  104559. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  104560. switch (interpolation) {
  104561. case "STEP" /* STEP */:
  104562. case "LINEAR" /* LINEAR */:
  104563. case "CUBICSPLINE" /* CUBICSPLINE */: {
  104564. break;
  104565. }
  104566. default: {
  104567. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  104568. }
  104569. }
  104570. var inputData;
  104571. var outputData;
  104572. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  104573. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  104574. sampler._data = Promise.all([
  104575. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  104576. inputData = data;
  104577. }),
  104578. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  104579. outputData = data;
  104580. })
  104581. ]).then(function () {
  104582. return {
  104583. input: inputData,
  104584. interpolation: interpolation,
  104585. output: outputData,
  104586. };
  104587. });
  104588. return sampler._data;
  104589. };
  104590. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  104591. if (buffer._data) {
  104592. return buffer._data;
  104593. }
  104594. if (!buffer.uri) {
  104595. throw new Error(context + ": Uri is missing");
  104596. }
  104597. buffer._data = this._loadUriAsync(context, buffer.uri);
  104598. return buffer._data;
  104599. };
  104600. /**
  104601. * @ignore
  104602. */
  104603. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  104604. if (bufferView._data) {
  104605. return bufferView._data;
  104606. }
  104607. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  104608. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  104609. try {
  104610. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  104611. }
  104612. catch (e) {
  104613. throw new Error(context + ": " + e.message);
  104614. }
  104615. });
  104616. return bufferView._data;
  104617. };
  104618. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  104619. if (accessor.sparse) {
  104620. throw new Error(context + ": Sparse accessors are not currently supported");
  104621. }
  104622. if (accessor._data) {
  104623. return accessor._data;
  104624. }
  104625. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104626. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  104627. var buffer = data.buffer;
  104628. var byteOffset = data.byteOffset + (accessor.byteOffset || 0);
  104629. var length = GLTFLoader._GetNumComponents(context, accessor.type) * accessor.count;
  104630. try {
  104631. switch (accessor.componentType) {
  104632. case 5120 /* BYTE */: {
  104633. return new Int8Array(buffer, byteOffset, length);
  104634. }
  104635. case 5121 /* UNSIGNED_BYTE */: {
  104636. return new Uint8Array(buffer, byteOffset, length);
  104637. }
  104638. case 5122 /* SHORT */: {
  104639. return new Int16Array(buffer, byteOffset, length);
  104640. }
  104641. case 5123 /* UNSIGNED_SHORT */: {
  104642. return new Uint16Array(buffer, byteOffset, length);
  104643. }
  104644. case 5125 /* UNSIGNED_INT */: {
  104645. return new Uint32Array(buffer, byteOffset, length);
  104646. }
  104647. case 5126 /* FLOAT */: {
  104648. return new Float32Array(buffer, byteOffset, length);
  104649. }
  104650. default: {
  104651. throw new Error(context + ": Invalid accessor component type " + accessor.componentType);
  104652. }
  104653. }
  104654. }
  104655. catch (e) {
  104656. throw new Error(context + ": " + e);
  104657. }
  104658. });
  104659. return accessor._data;
  104660. };
  104661. /**
  104662. * @ignore
  104663. */
  104664. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  104665. var _this = this;
  104666. if (bufferView._babylonBuffer) {
  104667. return bufferView._babylonBuffer;
  104668. }
  104669. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  104670. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  104671. });
  104672. return bufferView._babylonBuffer;
  104673. };
  104674. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  104675. var _this = this;
  104676. if (accessor.sparse) {
  104677. throw new Error(context + ": Sparse accessors are not currently supported");
  104678. }
  104679. if (accessor._babylonVertexBuffer) {
  104680. return accessor._babylonVertexBuffer;
  104681. }
  104682. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  104683. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView, kind).then(function (buffer) {
  104684. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  104685. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  104686. });
  104687. return accessor._babylonVertexBuffer;
  104688. };
  104689. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  104690. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  104691. if (!babylonMaterial) {
  104692. babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, "__gltf_default", drawMode);
  104693. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104694. babylonMaterial.metallic = 1;
  104695. babylonMaterial.roughness = 1;
  104696. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104697. }
  104698. return babylonMaterial;
  104699. };
  104700. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  104701. var promises = new Array();
  104702. // Ensure metallic workflow
  104703. babylonMaterial.metallic = 1;
  104704. babylonMaterial.roughness = 1;
  104705. var properties = material.pbrMetallicRoughness;
  104706. if (properties) {
  104707. if (properties.baseColorFactor) {
  104708. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  104709. babylonMaterial.alpha = properties.baseColorFactor[3];
  104710. }
  104711. else {
  104712. babylonMaterial.albedoColor = BABYLON.Color3.White();
  104713. }
  104714. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  104715. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  104716. if (properties.baseColorTexture) {
  104717. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  104718. babylonMaterial.albedoTexture = texture;
  104719. }));
  104720. }
  104721. if (properties.metallicRoughnessTexture) {
  104722. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  104723. babylonMaterial.metallicTexture = texture;
  104724. }));
  104725. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  104726. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  104727. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  104728. }
  104729. }
  104730. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  104731. return Promise.all(promises).then(function () { });
  104732. };
  104733. /**
  104734. * @ignore
  104735. */
  104736. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  104737. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  104738. if (promise) {
  104739. return promise;
  104740. }
  104741. material._babylonData = material._babylonData || {};
  104742. var babylonData = material._babylonData[babylonDrawMode];
  104743. if (!babylonData) {
  104744. var promises = new Array();
  104745. var name_3 = material.name || "materialSG_" + material._index;
  104746. var babylonMaterial = this._createMaterial(BABYLON.PBRMaterial, name_3, babylonDrawMode);
  104747. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  104748. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  104749. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  104750. babylonData = {
  104751. material: babylonMaterial,
  104752. meshes: [],
  104753. loaded: Promise.all(promises).then(function () { })
  104754. };
  104755. material._babylonData[babylonDrawMode] = babylonData;
  104756. }
  104757. babylonData.meshes.push(babylonMesh);
  104758. assign(babylonData.material);
  104759. return babylonData.loaded;
  104760. };
  104761. /**
  104762. * @ignore
  104763. */
  104764. GLTFLoader.prototype._createMaterial = function (type, name, drawMode) {
  104765. var babylonMaterial = new type(name, this._babylonScene);
  104766. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  104767. babylonMaterial.fillMode = drawMode;
  104768. return babylonMaterial;
  104769. };
  104770. /**
  104771. * @ignore
  104772. */
  104773. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  104774. var promises = new Array();
  104775. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  104776. if (material.doubleSided) {
  104777. babylonMaterial.backFaceCulling = false;
  104778. babylonMaterial.twoSidedLighting = true;
  104779. }
  104780. if (material.normalTexture) {
  104781. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  104782. babylonMaterial.bumpTexture = texture;
  104783. }));
  104784. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  104785. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  104786. if (material.normalTexture.scale != undefined) {
  104787. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  104788. }
  104789. }
  104790. if (material.occlusionTexture) {
  104791. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  104792. babylonMaterial.ambientTexture = texture;
  104793. }));
  104794. babylonMaterial.useAmbientInGrayScale = true;
  104795. if (material.occlusionTexture.strength != undefined) {
  104796. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  104797. }
  104798. }
  104799. if (material.emissiveTexture) {
  104800. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  104801. babylonMaterial.emissiveTexture = texture;
  104802. }));
  104803. }
  104804. return Promise.all(promises).then(function () { });
  104805. };
  104806. /**
  104807. * @ignore
  104808. */
  104809. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  104810. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  104811. switch (alphaMode) {
  104812. case "OPAQUE" /* OPAQUE */: {
  104813. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  104814. break;
  104815. }
  104816. case "MASK" /* MASK */: {
  104817. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  104818. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  104819. if (babylonMaterial.albedoTexture) {
  104820. babylonMaterial.albedoTexture.hasAlpha = true;
  104821. }
  104822. break;
  104823. }
  104824. case "BLEND" /* BLEND */: {
  104825. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  104826. if (babylonMaterial.albedoTexture) {
  104827. babylonMaterial.albedoTexture.hasAlpha = true;
  104828. babylonMaterial.useAlphaFromAlbedoTexture = true;
  104829. }
  104830. break;
  104831. }
  104832. default: {
  104833. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  104834. }
  104835. }
  104836. };
  104837. /**
  104838. * @ignore
  104839. */
  104840. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  104841. var _this = this;
  104842. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  104843. context = "#/textures/" + textureInfo.index;
  104844. var promises = new Array();
  104845. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  104846. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  104847. var deferred = new BABYLON.Deferred();
  104848. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  104849. if (!_this._disposed) {
  104850. deferred.resolve();
  104851. }
  104852. }, function (message, exception) {
  104853. if (!_this._disposed) {
  104854. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  104855. }
  104856. });
  104857. promises.push(deferred.promise);
  104858. babylonTexture.name = texture.name || "texture" + texture._index;
  104859. babylonTexture.wrapU = samplerData.wrapU;
  104860. babylonTexture.wrapV = samplerData.wrapV;
  104861. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  104862. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  104863. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  104864. babylonTexture.updateURL(objectURL);
  104865. }));
  104866. assign(babylonTexture);
  104867. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  104868. return Promise.all(promises).then(function () { });
  104869. };
  104870. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  104871. if (!sampler._data) {
  104872. sampler._data = {
  104873. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  104874. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  104875. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  104876. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  104877. };
  104878. }
  104879. ;
  104880. return sampler._data;
  104881. };
  104882. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  104883. if (image._objectURL) {
  104884. return image._objectURL;
  104885. }
  104886. var promise;
  104887. if (image.uri) {
  104888. promise = this._loadUriAsync(context, image.uri);
  104889. }
  104890. else {
  104891. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  104892. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  104893. }
  104894. image._objectURL = promise.then(function (data) {
  104895. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  104896. });
  104897. return image._objectURL;
  104898. };
  104899. /**
  104900. * @ignore
  104901. */
  104902. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  104903. var _this = this;
  104904. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  104905. if (promise) {
  104906. return promise;
  104907. }
  104908. if (!GLTFLoader._ValidateUri(uri)) {
  104909. throw new Error(context + ": Uri '" + uri + "' is invalid");
  104910. }
  104911. if (BABYLON.Tools.IsBase64(uri)) {
  104912. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  104913. }
  104914. return new Promise(function (resolve, reject) {
  104915. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  104916. if (!_this._disposed) {
  104917. resolve(new Uint8Array(data));
  104918. }
  104919. }, function (event) {
  104920. if (!_this._disposed) {
  104921. try {
  104922. if (request && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  104923. request._lengthComputable = event.lengthComputable;
  104924. request._loaded = event.loaded;
  104925. request._total = event.total;
  104926. _this._onProgress();
  104927. }
  104928. }
  104929. catch (e) {
  104930. reject(e);
  104931. }
  104932. }
  104933. }, _this._babylonScene.database, true, function (request, exception) {
  104934. if (!_this._disposed) {
  104935. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  104936. }
  104937. });
  104938. _this._requests.push(request);
  104939. });
  104940. };
  104941. GLTFLoader.prototype._onProgress = function () {
  104942. if (!this._progressCallback) {
  104943. return;
  104944. }
  104945. var lengthComputable = true;
  104946. var loaded = 0;
  104947. var total = 0;
  104948. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  104949. var request = _a[_i];
  104950. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  104951. return;
  104952. }
  104953. lengthComputable = lengthComputable && request._lengthComputable;
  104954. loaded += request._loaded;
  104955. total += request._total;
  104956. }
  104957. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  104958. };
  104959. /**
  104960. * @ignore
  104961. */
  104962. GLTFLoader._GetProperty = function (context, array, index) {
  104963. if (!array || index == undefined || !array[index]) {
  104964. throw new Error(context + ": Failed to find index (" + index + ")");
  104965. }
  104966. return array[index];
  104967. };
  104968. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  104969. // Set defaults if undefined
  104970. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  104971. switch (mode) {
  104972. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  104973. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  104974. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  104975. default:
  104976. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  104977. return BABYLON.Texture.WRAP_ADDRESSMODE;
  104978. }
  104979. };
  104980. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  104981. // Set defaults if undefined
  104982. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  104983. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  104984. if (magFilter === 9729 /* LINEAR */) {
  104985. switch (minFilter) {
  104986. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  104987. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  104988. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  104989. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  104990. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  104991. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104992. default:
  104993. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  104994. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  104995. }
  104996. }
  104997. else {
  104998. if (magFilter !== 9728 /* NEAREST */) {
  104999. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  105000. }
  105001. switch (minFilter) {
  105002. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  105003. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  105004. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105005. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  105006. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  105007. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  105008. default:
  105009. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105010. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105011. }
  105012. }
  105013. };
  105014. GLTFLoader._GetNumComponents = function (context, type) {
  105015. switch (type) {
  105016. case "SCALAR": return 1;
  105017. case "VEC2": return 2;
  105018. case "VEC3": return 3;
  105019. case "VEC4": return 4;
  105020. case "MAT2": return 4;
  105021. case "MAT3": return 9;
  105022. case "MAT4": return 16;
  105023. }
  105024. throw new Error(context + ": Invalid type (" + type + ")");
  105025. };
  105026. GLTFLoader._ValidateUri = function (uri) {
  105027. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  105028. };
  105029. GLTFLoader._GetDrawMode = function (context, mode) {
  105030. if (mode == undefined) {
  105031. mode = 4 /* TRIANGLES */;
  105032. }
  105033. switch (mode) {
  105034. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  105035. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  105036. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  105037. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  105038. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  105039. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  105040. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  105041. }
  105042. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  105043. };
  105044. GLTFLoader.prototype._compileMaterialsAsync = function () {
  105045. var promises = new Array();
  105046. if (this._gltf.materials) {
  105047. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  105048. var material = _a[_i];
  105049. if (material._babylonData) {
  105050. for (var babylonDrawMode in material._babylonData) {
  105051. var babylonData = material._babylonData[babylonDrawMode];
  105052. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  105053. var babylonMesh = _c[_b];
  105054. // Ensure nonUniformScaling is set if necessary.
  105055. babylonMesh.computeWorldMatrix(true);
  105056. var babylonMaterial = babylonData.material;
  105057. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  105058. if (this.useClipPlane) {
  105059. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  105060. }
  105061. }
  105062. }
  105063. }
  105064. }
  105065. }
  105066. return Promise.all(promises).then(function () { });
  105067. };
  105068. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  105069. var promises = new Array();
  105070. var lights = this._babylonScene.lights;
  105071. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  105072. var light = lights_1[_i];
  105073. var generator = light.getShadowGenerator();
  105074. if (generator) {
  105075. promises.push(generator.forceCompilationAsync());
  105076. }
  105077. }
  105078. return Promise.all(promises).then(function () { });
  105079. };
  105080. GLTFLoader.prototype._clear = function () {
  105081. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105082. var request = _a[_i];
  105083. request.abort();
  105084. }
  105085. this._requests.length = 0;
  105086. if (this._gltf && this._gltf.images) {
  105087. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  105088. var image = _c[_b];
  105089. if (image._objectURL) {
  105090. image._objectURL.then(function (value) {
  105091. URL.revokeObjectURL(value);
  105092. });
  105093. image._objectURL = undefined;
  105094. }
  105095. }
  105096. }
  105097. delete this._gltf;
  105098. delete this._babylonScene;
  105099. this._completePromises.length = 0;
  105100. for (var name_4 in this._extensions) {
  105101. this._extensions[name_4].dispose();
  105102. }
  105103. this._extensions = {};
  105104. delete this._rootBabylonMesh;
  105105. delete this._progressCallback;
  105106. this.onMeshLoadedObservable.clear();
  105107. this.onTextureLoadedObservable.clear();
  105108. this.onMaterialLoadedObservable.clear();
  105109. };
  105110. /**
  105111. * @ignore
  105112. */
  105113. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  105114. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  105115. var name_5 = _a[_i];
  105116. var extension = this._extensions[name_5];
  105117. if (extension.enabled) {
  105118. var promise = actionAsync(extension);
  105119. if (promise) {
  105120. return promise;
  105121. }
  105122. }
  105123. }
  105124. return null;
  105125. };
  105126. GLTFLoader._Names = new Array();
  105127. GLTFLoader._Factories = {};
  105128. return GLTFLoader;
  105129. }());
  105130. GLTF2.GLTFLoader = GLTFLoader;
  105131. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  105132. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105133. })(BABYLON || (BABYLON = {}));
  105134. //# sourceMappingURL=babylon.glTFLoader.js.map
  105135. var BABYLON;
  105136. (function (BABYLON) {
  105137. var GLTF2;
  105138. (function (GLTF2) {
  105139. /**
  105140. * Abstract class that can be implemented to extend existing gltf loader behavior.
  105141. */
  105142. var GLTFLoaderExtension = /** @class */ (function () {
  105143. function GLTFLoaderExtension(loader) {
  105144. this.enabled = true;
  105145. this._loader = loader;
  105146. }
  105147. GLTFLoaderExtension.prototype.dispose = function () {
  105148. delete this._loader;
  105149. };
  105150. // #region Overridable Methods
  105151. /** Override this method to modify the default behavior for loading scenes. */
  105152. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  105153. /** Override this method to modify the default behavior for loading nodes. */
  105154. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  105155. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  105156. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  105157. /** Override this method to modify the default behavior for loading materials. */
  105158. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  105159. /** Override this method to modify the default behavior for loading uris. */
  105160. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  105161. // #endregion
  105162. /** Helper method called by a loader extension to load an glTF extension. */
  105163. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  105164. if (!property.extensions) {
  105165. return null;
  105166. }
  105167. var extensions = property.extensions;
  105168. var extension = extensions[this.name];
  105169. if (!extension) {
  105170. return null;
  105171. }
  105172. // Clear out the extension before executing the action to avoid recursing into the same property.
  105173. delete extensions[this.name];
  105174. try {
  105175. return actionAsync(context + "/extensions/" + this.name, extension);
  105176. }
  105177. finally {
  105178. // Restore the extension after executing the action.
  105179. extensions[this.name] = extension;
  105180. }
  105181. };
  105182. /** Helper method called by the loader to allow extensions to override loading scenes. */
  105183. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  105184. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  105185. };
  105186. /** Helper method called by the loader to allow extensions to override loading nodes. */
  105187. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  105188. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  105189. };
  105190. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  105191. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  105192. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  105193. };
  105194. /** Helper method called by the loader to allow extensions to override loading materials. */
  105195. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  105196. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  105197. };
  105198. /** Helper method called by the loader to allow extensions to override loading uris. */
  105199. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  105200. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  105201. };
  105202. return GLTFLoaderExtension;
  105203. }());
  105204. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  105205. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105206. })(BABYLON || (BABYLON = {}));
  105207. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105208. var BABYLON;
  105209. (function (BABYLON) {
  105210. var GLTF2;
  105211. (function (GLTF2) {
  105212. var Extensions;
  105213. (function (Extensions) {
  105214. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod
  105215. var NAME = "MSFT_lod";
  105216. var MSFT_lod = /** @class */ (function (_super) {
  105217. __extends(MSFT_lod, _super);
  105218. function MSFT_lod() {
  105219. var _this = _super !== null && _super.apply(this, arguments) || this;
  105220. _this.name = NAME;
  105221. /**
  105222. * Maximum number of LODs to load, starting from the lowest LOD.
  105223. */
  105224. _this.maxLODsToLoad = Number.MAX_VALUE;
  105225. _this._loadingNodeLOD = null;
  105226. _this._loadNodeSignals = {};
  105227. _this._loadingMaterialLOD = null;
  105228. _this._loadMaterialSignals = {};
  105229. return _this;
  105230. }
  105231. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  105232. var _this = this;
  105233. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105234. var firstPromise;
  105235. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  105236. var _loop_1 = function (indexLOD) {
  105237. var nodeLOD = nodeLODs[indexLOD];
  105238. if (indexLOD !== 0) {
  105239. _this._loadingNodeLOD = nodeLOD;
  105240. if (!_this._loadNodeSignals[nodeLOD._index]) {
  105241. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  105242. }
  105243. }
  105244. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  105245. if (indexLOD !== 0) {
  105246. var previousNodeLOD = nodeLODs[indexLOD - 1];
  105247. if (previousNodeLOD._babylonMesh) {
  105248. previousNodeLOD._babylonMesh.dispose(false, true);
  105249. delete previousNodeLOD._babylonMesh;
  105250. }
  105251. }
  105252. if (indexLOD !== nodeLODs.length - 1) {
  105253. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  105254. if (_this._loadNodeSignals[nodeIndex]) {
  105255. _this._loadNodeSignals[nodeIndex].resolve();
  105256. delete _this._loadNodeSignals[nodeIndex];
  105257. }
  105258. }
  105259. });
  105260. if (indexLOD === 0) {
  105261. firstPromise = promise;
  105262. }
  105263. else {
  105264. _this._loader._completePromises.push(promise);
  105265. _this._loadingNodeLOD = null;
  105266. }
  105267. };
  105268. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  105269. _loop_1(indexLOD);
  105270. }
  105271. return firstPromise;
  105272. });
  105273. };
  105274. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105275. var _this = this;
  105276. // Don't load material LODs if already loading a node LOD.
  105277. if (this._loadingNodeLOD) {
  105278. return null;
  105279. }
  105280. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105281. var firstPromise;
  105282. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  105283. var _loop_2 = function (indexLOD) {
  105284. var materialLOD = materialLODs[indexLOD];
  105285. if (indexLOD !== 0) {
  105286. _this._loadingMaterialLOD = materialLOD;
  105287. if (!_this._loadMaterialSignals[materialLOD._index]) {
  105288. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  105289. }
  105290. }
  105291. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  105292. if (indexLOD !== 0) {
  105293. var babylonDataLOD = materialLOD._babylonData;
  105294. assign(babylonDataLOD[babylonDrawMode].material);
  105295. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  105296. if (previousBabylonDataLOD[babylonDrawMode]) {
  105297. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  105298. delete previousBabylonDataLOD[babylonDrawMode];
  105299. }
  105300. }
  105301. if (indexLOD !== materialLODs.length - 1) {
  105302. var materialIndex = materialLODs[indexLOD + 1]._index;
  105303. if (_this._loadMaterialSignals[materialIndex]) {
  105304. _this._loadMaterialSignals[materialIndex].resolve();
  105305. delete _this._loadMaterialSignals[materialIndex];
  105306. }
  105307. }
  105308. });
  105309. if (indexLOD === 0) {
  105310. firstPromise = promise;
  105311. }
  105312. else {
  105313. _this._loader._completePromises.push(promise);
  105314. _this._loadingMaterialLOD = null;
  105315. }
  105316. };
  105317. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  105318. _loop_2(indexLOD);
  105319. }
  105320. return firstPromise;
  105321. });
  105322. };
  105323. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  105324. var _this = this;
  105325. // Defer the loading of uris if loading a material or node LOD.
  105326. if (this._loadingMaterialLOD) {
  105327. var index = this._loadingMaterialLOD._index;
  105328. return this._loadMaterialSignals[index].promise.then(function () {
  105329. return _this._loader._loadUriAsync(context, uri);
  105330. });
  105331. }
  105332. else if (this._loadingNodeLOD) {
  105333. var index = this._loadingNodeLOD._index;
  105334. return this._loadNodeSignals[index].promise.then(function () {
  105335. return _this._loader._loadUriAsync(context, uri);
  105336. });
  105337. }
  105338. return null;
  105339. };
  105340. /**
  105341. * Gets an array of LOD properties from lowest to highest.
  105342. */
  105343. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  105344. if (this.maxLODsToLoad <= 0) {
  105345. throw new Error("maxLODsToLoad must be greater than zero");
  105346. }
  105347. var properties = new Array();
  105348. for (var i = ids.length - 1; i >= 0; i--) {
  105349. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  105350. if (properties.length === this.maxLODsToLoad) {
  105351. return properties;
  105352. }
  105353. }
  105354. properties.push(property);
  105355. return properties;
  105356. };
  105357. return MSFT_lod;
  105358. }(GLTF2.GLTFLoaderExtension));
  105359. Extensions.MSFT_lod = MSFT_lod;
  105360. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  105361. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105362. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105363. })(BABYLON || (BABYLON = {}));
  105364. //# sourceMappingURL=MSFT_lod.js.map
  105365. /** Module defining extensions to gltf */
  105366. var BABYLON;
  105367. (function (BABYLON) {
  105368. var GLTF2;
  105369. (function (GLTF2) {
  105370. var Extensions;
  105371. (function (Extensions) {
  105372. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  105373. var NAME = "KHR_draco_mesh_compression";
  105374. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  105375. __extends(KHR_draco_mesh_compression, _super);
  105376. function KHR_draco_mesh_compression(loader) {
  105377. var _this = _super.call(this, loader) || this;
  105378. _this.name = NAME;
  105379. _this._dracoCompression = null;
  105380. // Disable extension if decoder is not available.
  105381. if (!BABYLON.DracoCompression.DecoderAvailable) {
  105382. _this.enabled = false;
  105383. }
  105384. return _this;
  105385. }
  105386. KHR_draco_mesh_compression.prototype.dispose = function () {
  105387. if (this._dracoCompression) {
  105388. this._dracoCompression.dispose();
  105389. }
  105390. _super.prototype.dispose.call(this);
  105391. };
  105392. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  105393. var _this = this;
  105394. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  105395. if (primitive.mode != undefined) {
  105396. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  105397. primitive.mode !== 4 /* TRIANGLES */) {
  105398. throw new Error(context + ": Unsupported mode " + primitive.mode);
  105399. }
  105400. // TODO: handle triangle strips
  105401. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  105402. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  105403. }
  105404. }
  105405. var attributes = {};
  105406. var loadAttribute = function (name, kind) {
  105407. var uniqueId = extension.attributes[name];
  105408. if (uniqueId == undefined) {
  105409. return;
  105410. }
  105411. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  105412. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  105413. babylonMesh._delayInfo.push(kind);
  105414. }
  105415. attributes[kind] = uniqueId;
  105416. };
  105417. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  105418. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  105419. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  105420. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  105421. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  105422. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  105423. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  105424. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  105425. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  105426. if (!bufferView._dracoBabylonGeometry) {
  105427. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105428. if (!_this._dracoCompression) {
  105429. _this._dracoCompression = new BABYLON.DracoCompression();
  105430. }
  105431. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  105432. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  105433. babylonVertexData.applyToGeometry(babylonGeometry);
  105434. return babylonGeometry;
  105435. }).catch(function (error) {
  105436. throw new Error(context + ": " + error.message);
  105437. });
  105438. });
  105439. }
  105440. return bufferView._dracoBabylonGeometry;
  105441. });
  105442. };
  105443. return KHR_draco_mesh_compression;
  105444. }(GLTF2.GLTFLoaderExtension));
  105445. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  105446. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  105447. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105448. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105449. })(BABYLON || (BABYLON = {}));
  105450. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  105451. var BABYLON;
  105452. (function (BABYLON) {
  105453. var GLTF2;
  105454. (function (GLTF2) {
  105455. var Extensions;
  105456. (function (Extensions) {
  105457. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  105458. var NAME = "KHR_materials_pbrSpecularGlossiness";
  105459. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  105460. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  105461. function KHR_materials_pbrSpecularGlossiness() {
  105462. var _this = _super !== null && _super.apply(this, arguments) || this;
  105463. _this.name = NAME;
  105464. return _this;
  105465. }
  105466. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105467. var _this = this;
  105468. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105469. material._babylonData = material._babylonData || {};
  105470. var babylonData = material._babylonData[babylonDrawMode];
  105471. if (!babylonData) {
  105472. var promises = new Array();
  105473. var name_1 = material.name || "materialSG_" + material._index;
  105474. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  105475. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105476. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  105477. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105478. babylonData = {
  105479. material: babylonMaterial,
  105480. meshes: [],
  105481. loaded: Promise.all(promises).then(function () { })
  105482. };
  105483. material._babylonData[babylonDrawMode] = babylonData;
  105484. }
  105485. babylonData.meshes.push(babylonMesh);
  105486. assign(babylonData.material);
  105487. return babylonData.loaded;
  105488. });
  105489. };
  105490. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  105491. var promises = new Array();
  105492. if (properties.diffuseFactor) {
  105493. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  105494. babylonMaterial.alpha = properties.diffuseFactor[3];
  105495. }
  105496. else {
  105497. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105498. }
  105499. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  105500. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  105501. if (properties.diffuseTexture) {
  105502. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  105503. babylonMaterial.albedoTexture = texture;
  105504. }));
  105505. }
  105506. if (properties.specularGlossinessTexture) {
  105507. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  105508. babylonMaterial.reflectivityTexture = texture;
  105509. }));
  105510. babylonMaterial.reflectivityTexture.hasAlpha = true;
  105511. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  105512. }
  105513. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105514. return Promise.all(promises).then(function () { });
  105515. };
  105516. return KHR_materials_pbrSpecularGlossiness;
  105517. }(GLTF2.GLTFLoaderExtension));
  105518. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  105519. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  105520. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105521. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105522. })(BABYLON || (BABYLON = {}));
  105523. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  105524. var BABYLON;
  105525. (function (BABYLON) {
  105526. var GLTF2;
  105527. (function (GLTF2) {
  105528. var Extensions;
  105529. (function (Extensions) {
  105530. // https://github.com/donmccurdy/glTF/tree/feat-khr-materials-cmnConstant/extensions/2.0/Khronos/KHR_materials_unlit
  105531. var NAME = "KHR_materials_unlit";
  105532. var KHR_materials_unlit = /** @class */ (function (_super) {
  105533. __extends(KHR_materials_unlit, _super);
  105534. function KHR_materials_unlit() {
  105535. var _this = _super !== null && _super.apply(this, arguments) || this;
  105536. _this.name = NAME;
  105537. return _this;
  105538. }
  105539. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105540. var _this = this;
  105541. return this._loadExtensionAsync(context, material, function () {
  105542. material._babylonData = material._babylonData || {};
  105543. var babylonData = material._babylonData[babylonDrawMode];
  105544. if (!babylonData) {
  105545. var name_1 = material.name || "materialUnlit_" + material._index;
  105546. var babylonMaterial = _this._loader._createMaterial(BABYLON.PBRMaterial, name_1, babylonDrawMode);
  105547. babylonMaterial.unlit = true;
  105548. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  105549. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105550. babylonData = {
  105551. material: babylonMaterial,
  105552. meshes: [],
  105553. loaded: promise
  105554. };
  105555. material._babylonData[babylonDrawMode] = babylonData;
  105556. }
  105557. babylonData.meshes.push(babylonMesh);
  105558. assign(babylonData.material);
  105559. return babylonData.loaded;
  105560. });
  105561. };
  105562. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  105563. var promises = new Array();
  105564. // Ensure metallic workflow
  105565. babylonMaterial.metallic = 1;
  105566. babylonMaterial.roughness = 1;
  105567. var properties = material.pbrMetallicRoughness;
  105568. if (properties) {
  105569. if (properties.baseColorFactor) {
  105570. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105571. babylonMaterial.alpha = properties.baseColorFactor[3];
  105572. }
  105573. else {
  105574. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105575. }
  105576. if (properties.baseColorTexture) {
  105577. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105578. babylonMaterial.albedoTexture = texture;
  105579. }));
  105580. }
  105581. }
  105582. if (material.doubleSided) {
  105583. babylonMaterial.backFaceCulling = false;
  105584. babylonMaterial.twoSidedLighting = true;
  105585. }
  105586. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105587. return Promise.all(promises).then(function () { });
  105588. };
  105589. return KHR_materials_unlit;
  105590. }(GLTF2.GLTFLoaderExtension));
  105591. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  105592. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  105593. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105594. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105595. })(BABYLON || (BABYLON = {}));
  105596. //# sourceMappingURL=KHR_materials_unlit.js.map
  105597. var BABYLON;
  105598. (function (BABYLON) {
  105599. var GLTF2;
  105600. (function (GLTF2) {
  105601. var Extensions;
  105602. (function (Extensions) {
  105603. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  105604. var NAME = "KHR_lights";
  105605. var LightType;
  105606. (function (LightType) {
  105607. LightType["AMBIENT"] = "ambient";
  105608. LightType["DIRECTIONAL"] = "directional";
  105609. LightType["POINT"] = "point";
  105610. LightType["SPOT"] = "spot";
  105611. })(LightType || (LightType = {}));
  105612. var KHR_lights = /** @class */ (function (_super) {
  105613. __extends(KHR_lights, _super);
  105614. function KHR_lights() {
  105615. var _this = _super !== null && _super.apply(this, arguments) || this;
  105616. _this.name = NAME;
  105617. return _this;
  105618. }
  105619. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  105620. var _this = this;
  105621. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  105622. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  105623. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105624. if (light.type !== LightType.AMBIENT) {
  105625. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  105626. }
  105627. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  105628. return promise;
  105629. });
  105630. };
  105631. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  105632. var _this = this;
  105633. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105634. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  105635. var babylonLight;
  105636. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  105637. var name = node._babylonMesh.name;
  105638. switch (light.type) {
  105639. case LightType.AMBIENT: {
  105640. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  105641. }
  105642. case LightType.DIRECTIONAL: {
  105643. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  105644. break;
  105645. }
  105646. case LightType.POINT: {
  105647. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  105648. break;
  105649. }
  105650. case LightType.SPOT: {
  105651. var spotLight = light;
  105652. // TODO: support inner and outer cone angles
  105653. //const innerConeAngle = spotLight.innerConeAngle || 0;
  105654. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  105655. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  105656. break;
  105657. }
  105658. default: {
  105659. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  105660. }
  105661. }
  105662. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  105663. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  105664. babylonLight.parent = node._babylonMesh;
  105665. return promise;
  105666. });
  105667. };
  105668. Object.defineProperty(KHR_lights.prototype, "_lights", {
  105669. get: function () {
  105670. var extensions = this._loader._gltf.extensions;
  105671. if (!extensions || !extensions[this.name]) {
  105672. throw new Error("#/extensions: '" + this.name + "' not found");
  105673. }
  105674. var extension = extensions[this.name];
  105675. return extension.lights;
  105676. },
  105677. enumerable: true,
  105678. configurable: true
  105679. });
  105680. return KHR_lights;
  105681. }(GLTF2.GLTFLoaderExtension));
  105682. Extensions.KHR_lights = KHR_lights;
  105683. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  105684. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  105685. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105686. })(BABYLON || (BABYLON = {}));
  105687. //# sourceMappingURL=KHR_lights.js.map
  105688. return BABYLON;
  105689. });
  105690. /***/ }),
  105691. /* 35 */
  105692. /***/ (function(module, exports, __webpack_require__) {
  105693. /*!
  105694. * PEP v0.4.3 | https://github.com/jquery/PEP
  105695. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  105696. */
  105697. !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);
  105698. // define inherited MouseEvent properties
  105699. // skip bubbles and cancelable since they're set above in initEvent()
  105700. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  105701. // Spec requires that pointers without pressure specified use 0.5 for down
  105702. // state and 0 for up state.
  105703. var f=0;
  105704. // add x/y properties aliased to clientX/Y
  105705. // define the properties of the PointerEvent interface
  105706. 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(){
  105707. // only activate if this platform does not have pointer events
  105708. 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}})}/**
  105709. * This is the constructor for new PointerEvents.
  105710. *
  105711. * New Pointer Events must be given a type, and an optional dictionary of
  105712. * initialization properties.
  105713. *
  105714. * Due to certain platform requirements, events returned from the constructor
  105715. * identify as MouseEvents.
  105716. *
  105717. * @constructor
  105718. * @param {String} inType The type of the event to create.
  105719. * @param {Object} [inDict] An optional dictionary of initial event properties.
  105720. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  105721. */
  105722. 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},
  105723. // return value, key, map
  105724. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  105725. // MouseEvent
  105726. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  105727. // DOM Level 3
  105728. "buttons",
  105729. // PointerEvent
  105730. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  105731. // event instance
  105732. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  105733. // MouseEvent
  105734. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  105735. // DOM Level 3
  105736. 0,
  105737. // PointerEvent
  105738. 0,0,0,0,0,0,"",0,!1,
  105739. // event instance
  105740. "",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),
  105741. // Scope objects for native events.
  105742. // This exists for ease of testing.
  105743. eventSources:Object.create(null),eventSourceList:[],/**
  105744. * Add a new event source that will generate pointer events.
  105745. *
  105746. * `inSource` must contain an array of event names named `events`, and
  105747. * functions with the names specified in the `events` array.
  105748. * @param {string} name A name for the event source
  105749. * @param {Object} source A new source of platform events.
  105750. */
  105751. 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++)
  105752. // call eventsource register
  105753. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  105754. // call eventsource register
  105755. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  105756. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  105757. return!1}},
  105758. // EVENTS
  105759. 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)},
  105760. // LISTENER LOGIC
  105761. eventHandler:function(a){
  105762. // This is used to prevent multiple dispatch of pointerevents from
  105763. // platform events. This can happen when two elements in different scopes
  105764. // are set up to create pointer events, which is relevant to Shadow DOM.
  105765. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  105766. // set up event listeners
  105767. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  105768. // remove event listeners
  105769. 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)},
  105770. // EVENT CREATION AND TRACKING
  105771. /**
  105772. * Creates a new Event of type `inType`, based on the information in
  105773. * `inEvent`.
  105774. *
  105775. * @param {string} inType A string representing the type of event to create
  105776. * @param {Event} inEvent A platform event with a target
  105777. * @return {Event} A PointerEvent of type `inType`
  105778. */
  105779. makeEvent:function(b,c){
  105780. // relatedTarget must be null if pointer is captured
  105781. 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},
  105782. // make and dispatch an event in one call
  105783. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  105784. * Returns a snapshot of inEvent, with writable properties.
  105785. *
  105786. * @param {Event} inEvent An event that contains properties to copy.
  105787. * @return {Object} An object containing shallow copies of `inEvent`'s
  105788. * properties.
  105789. */
  105790. 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],
  105791. // Work around SVGInstanceElement shadow tree
  105792. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  105793. // This is the behavior implemented by Firefox.
  105794. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  105795. // keep the semantics of preventDefault
  105796. 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){
  105797. // Order of conditions due to document.contains() missing in IE.
  105798. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  105799. // Touch: Do not propagate if node is detached.
  105800. 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)}},/**
  105801. * Dispatches the event to its target.
  105802. *
  105803. * @param {Event} inEvent The event to be dispatched.
  105804. * @return {Boolean} True if an event handler returns true, false otherwise.
  105805. */
  105806. 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(
  105807. // is element a shadow host?
  105808. e=this.targetingShadow(f);e;){if(
  105809. // find the the element inside the shadow root
  105810. d=e.elementFromPoint(b,c)){
  105811. // shadowed element may contain a shadow root
  105812. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  105813. // check for older shadows
  105814. e=this.olderShadow(e)}
  105815. // light dom element is the target
  105816. return f}},owner:function(a){
  105817. // walk up until you hit the shadow root or document
  105818. for(var b=a;b.parentNode;)b=b.parentNode;
  105819. // the owner element is expected to be a Document or ShadowRoot
  105820. 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);
  105821. // if x, y is not in this root, fall back to document search
  105822. 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){
  105823. // Only watch scopes that can target find, as these are top-level.
  105824. // Otherwise we can see duplicate additions and removals that add noise.
  105825. //
  105826. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  105827. // a removal without an insertion when a node is redistributed among
  105828. // shadows. Since it all ends up correct in the document, watching only
  105829. // the document will yield the correct mutations to watch.
  105830. 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))},
  105831. // register all touch-action = none nodes on document load
  105832. 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){
  105833. // find children with touch-action
  105834. var b=x(a,this.findElements,this);
  105835. // flatten the list
  105836. // make sure the added nodes are accounted for
  105837. 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){}
  105838. // handler block for native mouse events
  105839. 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:[],
  105840. // collide with the global mouse listener
  105841. 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++){
  105842. // simulated mouse events will be swallowed near a primary touchend
  105843. 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);
  105844. // Update buttons state after possible out-of-document mouseup.
  105845. 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];
  105846. // Produces wrong state of buttons in Browsers without `buttons` support
  105847. // when a mouse button that was pressed outside the document is released
  105848. // inside and other buttons are still pressed down.
  105849. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  105850. // Support: Firefox <=44 only
  105851. // FF Ubuntu includes the lifted button in the `buttons` property on
  105852. // mouseup.
  105853. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  105854. 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),
  105855. // set touch-action on shadows as well
  105856. 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),
  105857. // remove touch-action from shadow
  105858. 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);
  105859. // simply update scrollType if listeners are already established
  105860. 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){
  105861. // set primary touch if there no pointers, or the only pointer is the mouse
  105862. (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,
  105863. // forward modifier keys
  105864. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  105865. // forward touch preventDefaults
  105866. 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))},
  105867. // For single axis scrollers, determines whether the element should emit
  105868. // pointer events or behave as a scroller
  105869. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  105870. // this element is a touch-action: none, should never scroll
  105871. b=!1;else if("XY"===c)
  105872. // this element should always scroll
  105873. 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]);
  105874. // if delta in the scroll axis > delta other axis, scroll instead of
  105875. // making events
  105876. 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},
  105877. // In some instances, a touchstart can happen without a touchend. This
  105878. // leaves the pointermap in a broken state.
  105879. // Therefore, on every touchstart, we remove the touches that did not fire a
  105880. // touchend event.
  105881. // To keep state globally consistent, we fire a
  105882. // pointercancel for this "abandoned" touch
  105883. vacuumTouches:function(a){var b=a.touches;
  105884. // pointermap.size should be < tl.length here, as the touchstart has not
  105885. // been processed yet.
  105886. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  105887. // Never remove pointerId == 1, which is mouse.
  105888. // Touch identifiers are 2 smaller than their pointerId, which is the
  105889. // index in pointermap.
  105890. 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);
  105891. // a finger drifted off the screen, ignore it
  105892. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  105893. // recover from retargeting by shadow
  105894. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  105895. // clean up case when finger leaves the screen
  105896. 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)},
  105897. // prevent synth mouse events from creating pointer events
  105898. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  105899. // only the primary finger will synth mouse events
  105900. if(this.isPrimaryTouch(c)){
  105901. // remember x/y of last touch
  105902. 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});
  105903. /***/ }),
  105904. /* 36 */
  105905. /***/ (function(module, exports, __webpack_require__) {
  105906. "use strict";
  105907. Object.defineProperty(exports, "__esModule", { value: true });
  105908. var defaultViewer_1 = __webpack_require__(5);
  105909. var mappers_1 = __webpack_require__(1);
  105910. /**
  105911. * Select all HTML tags on the page that match the selector and initialize a viewer
  105912. *
  105913. * @param selector the selector to initialize the viewer on (default is 'babylon')
  105914. */
  105915. function InitTags(selector) {
  105916. if (selector === void 0) { selector = 'babylon'; }
  105917. var elements = document.querySelectorAll(selector);
  105918. for (var i = 0; i < elements.length; ++i) {
  105919. var element = elements.item(i);
  105920. // get the html configuration
  105921. var configMapper = mappers_1.mapperManager.getMapper('dom');
  105922. var config = configMapper.map(element);
  105923. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  105924. }
  105925. }
  105926. exports.InitTags = InitTags;
  105927. /***/ })
  105928. /******/ ]);
  105929. return BabylonViewer;
  105930. });